032ecaa850e6bb7d6d9d47dcbc8e9690975167f5
[lhc/web/wiklou.git] / includes / parser / Parser.php
1 <?php
2 /**
3 * @defgroup Parser Parser
4 *
5 * @file
6 * @ingroup Parser
7 * File for Parser and related classes
8 */
9
10
11 /**
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
16 *
17 * <pre>
18 * There are five main entry points into the Parser class:
19 * parse()
20 * produces HTML output
21 * preSaveTransform().
22 * produces altered wiki markup.
23 * preprocess()
24 * removes HTML comments and expands templates
25 * cleanSig()
26 * Cleans a signature before saving it to preferences
27 * extractSections()
28 * Extracts sections from an article for section editing
29 *
30 * Globals used:
31 * objects: $wgLang, $wgContLang
32 *
33 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
34 *
35 * settings:
36 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
37 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
38 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
39 * $wgMaxArticleSize*
40 *
41 * * only within ParserOptions
42 * </pre>
43 *
44 * @ingroup Parser
45 */
46 class Parser
47 {
48 /**
49 * Update this version number when the ParserOutput format
50 * changes in an incompatible way, so the parser cache
51 * can automatically discard old data.
52 */
53 const VERSION = '1.6.4';
54
55 # Flags for Parser::setFunctionHook
56 # Also available as global constants from Defines.php
57 const SFH_NO_HASH = 1;
58 const SFH_OBJECT_ARGS = 2;
59
60 # Constants needed for external link processing
61 # Everything except bracket, space, or control characters
62 const EXT_LINK_URL_CLASS = '[^][<>"\\x00-\\x20\\x7F]';
63 const EXT_IMAGE_REGEX = '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
64 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
65
66 // State constants for the definition list colon extraction
67 const COLON_STATE_TEXT = 0;
68 const COLON_STATE_TAG = 1;
69 const COLON_STATE_TAGSTART = 2;
70 const COLON_STATE_CLOSETAG = 3;
71 const COLON_STATE_TAGSLASH = 4;
72 const COLON_STATE_COMMENT = 5;
73 const COLON_STATE_COMMENTDASH = 6;
74 const COLON_STATE_COMMENTDASHDASH = 7;
75
76 // Flags for preprocessToDom
77 const PTD_FOR_INCLUSION = 1;
78
79 // Allowed values for $this->mOutputType
80 // Parameter to startExternalParse().
81 const OT_HTML = 1;
82 const OT_WIKI = 2;
83 const OT_PREPROCESS = 3;
84 const OT_MSG = 3;
85
86 // Marker Suffix needs to be accessible staticly.
87 const MARKER_SUFFIX = "-QINU\x7f";
88
89 /**#@+
90 * @private
91 */
92 # Persistent:
93 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
94 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex, $mPreprocessor,
95 $mExtLinkBracketedRegex, $mUrlProtocols, $mDefaultStripList, $mVarCache, $mConf;
96
97
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
100 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mLinkHolders, $mLinkID;
102 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
103 var $mTplExpandCache; // empty-frame expansion cache
104 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
105 var $mExpensiveFunctionCount; // number of expensive parser function calls
106
107 # Temporary
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions, // ParserOptions object
110 $mTitle, // Title context, used for self-link rendering and similar things
111 $mOutputType, // Output type, one of the OT_xxx constants
112 $ot, // Shortcut alias, see setOutputType()
113 $mRevisionId, // ID to display in {{REVISIONID}} tags
114 $mRevisionTimestamp, // The timestamp of the specified revision ID
115 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
116
117 /**#@-*/
118
119 /**
120 * Constructor
121 *
122 * @public
123 */
124 function __construct( $conf = array() ) {
125 $this->mConf = $conf;
126 $this->mTagHooks = array();
127 $this->mTransparentTagHooks = array();
128 $this->mFunctionHooks = array();
129 $this->mFunctionSynonyms = array( 0 => array(), 1 => array() );
130 $this->mDefaultStripList = $this->mStripList = array( 'nowiki', 'gallery' );
131 $this->mUrlProtocols = wfUrlProtocols();
132 $this->mExtLinkBracketedRegex = '/\[(\b(' . wfUrlProtocols() . ')'.
133 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
134 $this->mVarCache = array();
135 if ( isset( $conf['preprocessorClass'] ) ) {
136 $this->mPreprocessorClass = $conf['preprocessorClass'];
137 } elseif ( extension_loaded( 'dom' ) ) {
138 $this->mPreprocessorClass = 'Preprocessor_DOM';
139 } else {
140 $this->mPreprocessorClass = 'Preprocessor_Hash';
141 }
142 $this->mMarkerIndex = 0;
143 $this->mFirstCall = true;
144 }
145
146 /**
147 * Reduce memory usage to reduce the impact of circular references
148 */
149 function __destruct() {
150 if ( isset( $this->mLinkHolders ) ) {
151 $this->mLinkHolders->__destruct();
152 }
153 foreach ( $this as $name => $value ) {
154 unset( $this->$name );
155 }
156 }
157
158 /**
159 * Do various kinds of initialisation on the first call of the parser
160 */
161 function firstCallInit() {
162 if ( !$this->mFirstCall ) {
163 return;
164 }
165 $this->mFirstCall = false;
166
167 wfProfileIn( __METHOD__ );
168
169 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
170 CoreParserFunctions::register( $this );
171 $this->initialiseVariables();
172
173 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
174 wfProfileOut( __METHOD__ );
175 }
176
177 /**
178 * Clear Parser state
179 *
180 * @private
181 */
182 function clearState() {
183 wfProfileIn( __METHOD__ );
184 if ( $this->mFirstCall ) {
185 $this->firstCallInit();
186 }
187 $this->mOutput = new ParserOutput;
188 $this->mAutonumber = 0;
189 $this->mLastSection = '';
190 $this->mDTopen = false;
191 $this->mIncludeCount = array();
192 $this->mStripState = new StripState;
193 $this->mArgStack = false;
194 $this->mInPre = false;
195 $this->mLinkHolders = new LinkHolderArray( $this );
196 $this->mLinkID = 0;
197 $this->mRevisionTimestamp = $this->mRevisionId = null;
198
199 /**
200 * Prefix for temporary replacement strings for the multipass parser.
201 * \x07 should never appear in input as it's disallowed in XML.
202 * Using it at the front also gives us a little extra robustness
203 * since it shouldn't match when butted up against identifier-like
204 * string constructs.
205 *
206 * Must not consist of all title characters, or else it will change
207 * the behaviour of <nowiki> in a link.
208 */
209 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
210 # Changed to \x7f to allow XML double-parsing -- TS
211 $this->mUniqPrefix = "\x7fUNIQ" . self::getRandomString();
212
213
214 # Clear these on every parse, bug 4549
215 $this->mTplExpandCache = $this->mTplRedirCache = $this->mTplDomCache = array();
216
217 $this->mShowToc = true;
218 $this->mForceTocPosition = false;
219 $this->mIncludeSizes = array(
220 'post-expand' => 0,
221 'arg' => 0,
222 );
223 $this->mPPNodeCount = 0;
224 $this->mDefaultSort = false;
225 $this->mHeadings = array();
226 $this->mDoubleUnderscores = array();
227 $this->mExpensiveFunctionCount = 0;
228
229 # Fix cloning
230 if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) {
231 $this->mPreprocessor = null;
232 }
233
234 wfRunHooks( 'ParserClearState', array( &$this ) );
235 wfProfileOut( __METHOD__ );
236 }
237
238 function setOutputType( $ot ) {
239 $this->mOutputType = $ot;
240 // Shortcut alias
241 $this->ot = array(
242 'html' => $ot == self::OT_HTML,
243 'wiki' => $ot == self::OT_WIKI,
244 'pre' => $ot == self::OT_PREPROCESS,
245 );
246 }
247
248 /**
249 * Set the context title
250 */
251 function setTitle( $t ) {
252 if ( !$t || $t instanceof FakeTitle ) {
253 $t = Title::newFromText( 'NO TITLE' );
254 }
255 if ( strval( $t->getFragment() ) !== '' ) {
256 # Strip the fragment to avoid various odd effects
257 $this->mTitle = clone $t;
258 $this->mTitle->setFragment( '' );
259 } else {
260 $this->mTitle = $t;
261 }
262 }
263
264 /**
265 * Accessor for mUniqPrefix.
266 *
267 * @public
268 */
269 function uniqPrefix() {
270 if( !isset( $this->mUniqPrefix ) ) {
271 // @fixme this is probably *horribly wrong*
272 // LanguageConverter seems to want $wgParser's uniqPrefix, however
273 // if this is called for a parser cache hit, the parser may not
274 // have ever been initialized in the first place.
275 // Not really sure what the heck is supposed to be going on here.
276 return '';
277 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
278 }
279 return $this->mUniqPrefix;
280 }
281
282 /**
283 * Convert wikitext to HTML
284 * Do not call this function recursively.
285 *
286 * @param $text String: text we want to parse
287 * @param $title A title object
288 * @param $options ParserOptions
289 * @param $linestart boolean
290 * @param $clearState boolean
291 * @param $revid Int: number to pass in {{REVISIONID}}
292 * @return ParserOutput a ParserOutput
293 */
294 public function parse( $text, Title $title, ParserOptions $options, $linestart = true, $clearState = true, $revid = null ) {
295 /**
296 * First pass--just handle <nowiki> sections, pass the rest off
297 * to internalParse() which does all the real work.
298 */
299
300 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
301 $fname = __METHOD__.'-' . wfGetCaller();
302 wfProfileIn( __METHOD__ );
303 wfProfileIn( $fname );
304
305 if ( $clearState ) {
306 $this->clearState();
307 }
308
309 $this->mOptions = $options;
310 $this->setTitle( $title );
311 $oldRevisionId = $this->mRevisionId;
312 $oldRevisionTimestamp = $this->mRevisionTimestamp;
313 if( $revid !== null ) {
314 $this->mRevisionId = $revid;
315 $this->mRevisionTimestamp = null;
316 }
317 $this->setOutputType( self::OT_HTML );
318 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
319 # No more strip!
320 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
321 $text = $this->internalParse( $text );
322 $text = $this->mStripState->unstripGeneral( $text );
323
324 # Clean up special characters, only run once, next-to-last before doBlockLevels
325 $fixtags = array(
326 # french spaces, last one Guillemet-left
327 # only if there is something before the space
328 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1&nbsp;\\2',
329 # french spaces, Guillemet-right
330 '/(\\302\\253) /' => '\\1&nbsp;',
331 '/&nbsp;(!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
332 );
333 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
334
335 $text = $this->doBlockLevels( $text, $linestart );
336
337 $this->replaceLinkHolders( $text );
338
339 # the position of the parserConvert() call should not be changed. it
340 # assumes that the links are all replaced and the only thing left
341 # is the <nowiki> mark.
342 # Side-effects: this calls $this->mOutput->setTitleText()
343 $text = $wgContLang->parserConvert( $text, $this );
344
345 $text = $this->mStripState->unstripNoWiki( $text );
346
347 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
348
349 //!JF Move to its own function
350
351 $uniq_prefix = $this->mUniqPrefix;
352 $matches = array();
353 $elements = array_keys( $this->mTransparentTagHooks );
354 $text = self::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
355
356 foreach( $matches as $marker => $data ) {
357 list( $element, $content, $params, $tag ) = $data;
358 $tagName = strtolower( $element );
359 if( isset( $this->mTransparentTagHooks[$tagName] ) ) {
360 $output = call_user_func_array( $this->mTransparentTagHooks[$tagName],
361 array( $content, $params, $this ) );
362 } else {
363 $output = $tag;
364 }
365 $this->mStripState->general->setPair( $marker, $output );
366 }
367 $text = $this->mStripState->unstripGeneral( $text );
368
369 $text = Sanitizer::normalizeCharReferences( $text );
370
371 if (($wgUseTidy and $this->mOptions->mTidy) or $wgAlwaysUseTidy) {
372 $text = self::tidy($text);
373 } else {
374 # attempt to sanitize at least some nesting problems
375 # (bug #2702 and quite a few others)
376 $tidyregs = array(
377 # ''Something [http://www.cool.com cool''] -->
378 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
379 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
380 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
381 # fix up an anchor inside another anchor, only
382 # at least for a single single nested link (bug 3695)
383 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
384 '\\1\\2</a>\\3</a>\\1\\4</a>',
385 # fix div inside inline elements- doBlockLevels won't wrap a line which
386 # contains a div, so fix it up here; replace
387 # div with escaped text
388 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
389 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
390 # remove empty italic or bold tag pairs, some
391 # introduced by rules above
392 '/<([bi])><\/\\1>/' => '',
393 );
394
395 $text = preg_replace(
396 array_keys( $tidyregs ),
397 array_values( $tidyregs ),
398 $text );
399 }
400 global $wgExpensiveParserFunctionLimit;
401 if ( $this->mExpensiveFunctionCount > $wgExpensiveParserFunctionLimit ) {
402 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount, $wgExpensiveParserFunctionLimit );
403 }
404
405 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
406
407 # Information on include size limits, for the benefit of users who try to skirt them
408 if ( $this->mOptions->getEnableLimitReport() ) {
409 global $wgExpensiveParserFunctionLimit;
410 $max = $this->mOptions->getMaxIncludeSize();
411 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
412 $limitReport =
413 "NewPP limit report\n" .
414 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
415 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
416 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
417 $PFreport;
418 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
419 $text .= "\n<!-- \n$limitReport-->\n";
420 }
421 $this->mOutput->setText( $text );
422 $this->mRevisionId = $oldRevisionId;
423 $this->mRevisionTimestamp = $oldRevisionTimestamp;
424 wfProfileOut( $fname );
425 wfProfileOut( __METHOD__ );
426
427 return $this->mOutput;
428 }
429
430 /**
431 * Recursive parser entry point that can be called from an extension tag
432 * hook.
433 */
434 function recursiveTagParse( $text ) {
435 wfProfileIn( __METHOD__ );
436 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
437 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
438 $text = $this->internalParse( $text );
439 wfProfileOut( __METHOD__ );
440 return $text;
441 }
442
443 /**
444 * Expand templates and variables in the text, producing valid, static wikitext.
445 * Also removes comments.
446 */
447 function preprocess( $text, $title, $options, $revid = null ) {
448 wfProfileIn( __METHOD__ );
449 $this->clearState();
450 $this->setOutputType( self::OT_PREPROCESS );
451 $this->mOptions = $options;
452 $this->setTitle( $title );
453 if( $revid !== null ) {
454 $this->mRevisionId = $revid;
455 }
456 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
457 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
458 $text = $this->replaceVariables( $text );
459 $text = $this->mStripState->unstripBoth( $text );
460 wfProfileOut( __METHOD__ );
461 return $text;
462 }
463
464 /**
465 * Get a random string
466 *
467 * @private
468 * @static
469 */
470 function getRandomString() {
471 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
472 }
473
474 function &getTitle() { return $this->mTitle; }
475 function getOptions() { return $this->mOptions; }
476 function getRevisionId() { return $this->mRevisionId; }
477 function getOutput() { return $this->mOutput; }
478 function nextLinkID() { return $this->mLinkID++; }
479
480 function getFunctionLang() {
481 global $wgLang, $wgContLang;
482
483 $target = $this->mOptions->getTargetLanguage();
484 if ( $target !== null ) {
485 return $target;
486 } else {
487 return $this->mOptions->getInterfaceMessage() ? $wgLang : $wgContLang;
488 }
489 }
490
491 /**
492 * Get a preprocessor object
493 */
494 function getPreprocessor() {
495 if ( !isset( $this->mPreprocessor ) ) {
496 $class = $this->mPreprocessorClass;
497 $this->mPreprocessor = new $class( $this );
498 }
499 return $this->mPreprocessor;
500 }
501
502 /**
503 * Replaces all occurrences of HTML-style comments and the given tags
504 * in the text with a random marker and returns the next text. The output
505 * parameter $matches will be an associative array filled with data in
506 * the form:
507 * 'UNIQ-xxxxx' => array(
508 * 'element',
509 * 'tag content',
510 * array( 'param' => 'x' ),
511 * '<element param="x">tag content</element>' ) )
512 *
513 * @param $elements list of element names. Comments are always extracted.
514 * @param $text Source text string.
515 * @param $uniq_prefix
516 *
517 * @public
518 * @static
519 */
520 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
521 static $n = 1;
522 $stripped = '';
523 $matches = array();
524
525 $taglist = implode( '|', $elements );
526 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
527
528 while ( '' != $text ) {
529 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
530 $stripped .= $p[0];
531 if( count( $p ) < 5 ) {
532 break;
533 }
534 if( count( $p ) > 5 ) {
535 // comment
536 $element = $p[4];
537 $attributes = '';
538 $close = '';
539 $inside = $p[5];
540 } else {
541 // tag
542 $element = $p[1];
543 $attributes = $p[2];
544 $close = $p[3];
545 $inside = $p[4];
546 }
547
548 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++) . self::MARKER_SUFFIX;
549 $stripped .= $marker;
550
551 if ( $close === '/>' ) {
552 // Empty element tag, <tag />
553 $content = null;
554 $text = $inside;
555 $tail = null;
556 } else {
557 if( $element === '!--' ) {
558 $end = '/(-->)/';
559 } else {
560 $end = "/(<\\/$element\\s*>)/i";
561 }
562 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
563 $content = $q[0];
564 if( count( $q ) < 3 ) {
565 # No end tag -- let it run out to the end of the text.
566 $tail = '';
567 $text = '';
568 } else {
569 $tail = $q[1];
570 $text = $q[2];
571 }
572 }
573
574 $matches[$marker] = array( $element,
575 $content,
576 Sanitizer::decodeTagAttributes( $attributes ),
577 "<$element$attributes$close$content$tail" );
578 }
579 return $stripped;
580 }
581
582 /**
583 * Get a list of strippable XML-like elements
584 */
585 function getStripList() {
586 global $wgRawHtml;
587 $elements = $this->mStripList;
588 if( $wgRawHtml ) {
589 $elements[] = 'html';
590 }
591 if( $this->mOptions->getUseTeX() ) {
592 $elements[] = 'math';
593 }
594 return $elements;
595 }
596
597 /**
598 * @deprecated use replaceVariables
599 */
600 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
601 return $text;
602 }
603
604 /**
605 * Restores pre, math, and other extensions removed by strip()
606 *
607 * always call unstripNoWiki() after this one
608 * @private
609 * @deprecated use $this->mStripState->unstrip()
610 */
611 function unstrip( $text, $state ) {
612 return $state->unstripGeneral( $text );
613 }
614
615 /**
616 * Always call this after unstrip() to preserve the order
617 *
618 * @private
619 * @deprecated use $this->mStripState->unstrip()
620 */
621 function unstripNoWiki( $text, $state ) {
622 return $state->unstripNoWiki( $text );
623 }
624
625 /**
626 * @deprecated use $this->mStripState->unstripBoth()
627 */
628 function unstripForHTML( $text ) {
629 return $this->mStripState->unstripBoth( $text );
630 }
631
632 /**
633 * Add an item to the strip state
634 * Returns the unique tag which must be inserted into the stripped text
635 * The tag will be replaced with the original text in unstrip()
636 *
637 * @private
638 */
639 function insertStripItem( $text ) {
640 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX;
641 $this->mMarkerIndex++;
642 $this->mStripState->general->setPair( $rnd, $text );
643 return $rnd;
644 }
645
646 /**
647 * Interface with html tidy, used if $wgUseTidy = true.
648 * If tidy isn't able to correct the markup, the original will be
649 * returned in all its glory with a warning comment appended.
650 *
651 * Either the external tidy program or the in-process tidy extension
652 * will be used depending on availability. Override the default
653 * $wgTidyInternal setting to disable the internal if it's not working.
654 *
655 * @param string $text Hideous HTML input
656 * @return string Corrected HTML output
657 * @public
658 * @static
659 */
660 function tidy( $text ) {
661 global $wgTidyInternal;
662 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
663 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
664 '<head><title>test</title></head><body>'.$text.'</body></html>';
665 if( $wgTidyInternal ) {
666 $correctedtext = self::internalTidy( $wrappedtext );
667 } else {
668 $correctedtext = self::externalTidy( $wrappedtext );
669 }
670 if( is_null( $correctedtext ) ) {
671 wfDebug( "Tidy error detected!\n" );
672 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
673 }
674 return $correctedtext;
675 }
676
677 /**
678 * Spawn an external HTML tidy process and get corrected markup back from it.
679 *
680 * @private
681 * @static
682 */
683 function externalTidy( $text ) {
684 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
685 wfProfileIn( __METHOD__ );
686
687 $cleansource = '';
688 $opts = ' -utf8';
689
690 $descriptorspec = array(
691 0 => array('pipe', 'r'),
692 1 => array('pipe', 'w'),
693 2 => array('file', wfGetNull(), 'a')
694 );
695 $pipes = array();
696 if( function_exists('proc_open') ) {
697 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
698 if (is_resource($process)) {
699 // Theoretically, this style of communication could cause a deadlock
700 // here. If the stdout buffer fills up, then writes to stdin could
701 // block. This doesn't appear to happen with tidy, because tidy only
702 // writes to stdout after it's finished reading from stdin. Search
703 // for tidyParseStdin and tidySaveStdout in console/tidy.c
704 fwrite($pipes[0], $text);
705 fclose($pipes[0]);
706 while (!feof($pipes[1])) {
707 $cleansource .= fgets($pipes[1], 1024);
708 }
709 fclose($pipes[1]);
710 proc_close($process);
711 }
712 }
713
714 wfProfileOut( __METHOD__ );
715
716 if( $cleansource == '' && $text != '') {
717 // Some kind of error happened, so we couldn't get the corrected text.
718 // Just give up; we'll use the source text and append a warning.
719 return null;
720 } else {
721 return $cleansource;
722 }
723 }
724
725 /**
726 * Use the HTML tidy PECL extension to use the tidy library in-process,
727 * saving the overhead of spawning a new process.
728 *
729 * 'pear install tidy' should be able to compile the extension module.
730 *
731 * @private
732 * @static
733 */
734 function internalTidy( $text ) {
735 global $wgTidyConf, $IP, $wgDebugTidy;
736 wfProfileIn( __METHOD__ );
737
738 $tidy = new tidy;
739 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
740 $tidy->cleanRepair();
741 if( $tidy->getStatus() == 2 ) {
742 // 2 is magic number for fatal error
743 // http://www.php.net/manual/en/function.tidy-get-status.php
744 $cleansource = null;
745 } else {
746 $cleansource = tidy_get_output( $tidy );
747 }
748 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
749 $cleansource .= "<!--\nTidy reports:\n" .
750 str_replace( '-->', '--&gt;', $tidy->errorBuffer ) .
751 "\n-->";
752 }
753
754 wfProfileOut( __METHOD__ );
755 return $cleansource;
756 }
757
758 /**
759 * parse the wiki syntax used to render tables
760 *
761 * @private
762 */
763 function doTableStuff ( $text ) {
764 wfProfileIn( __METHOD__ );
765
766 $lines = StringUtils::explode( "\n", $text );
767 $out = '';
768 $td_history = array (); // Is currently a td tag open?
769 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
770 $tr_history = array (); // Is currently a tr tag open?
771 $tr_attributes = array (); // history of tr attributes
772 $has_opened_tr = array(); // Did this table open a <tr> element?
773 $indent_level = 0; // indent level of the table
774
775 foreach ( $lines as $outLine ) {
776 $line = trim( $outLine );
777
778 if( $line == '' ) { // empty line, go to next line
779 $out .= $outLine."\n";
780 continue;
781 }
782 $first_character = $line[0];
783 $matches = array();
784
785 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
786 // First check if we are starting a new table
787 $indent_level = strlen( $matches[1] );
788
789 $attributes = $this->mStripState->unstripBoth( $matches[2] );
790 $attributes = Sanitizer::fixTagAttributes ( $attributes , 'table' );
791
792 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
793 array_push ( $td_history , false );
794 array_push ( $last_tag_history , '' );
795 array_push ( $tr_history , false );
796 array_push ( $tr_attributes , '' );
797 array_push ( $has_opened_tr , false );
798 } else if ( count ( $td_history ) == 0 ) {
799 // Don't do any of the following
800 $out .= $outLine."\n";
801 continue;
802 } else if ( substr ( $line , 0 , 2 ) === '|}' ) {
803 // We are ending a table
804 $line = '</table>' . substr ( $line , 2 );
805 $last_tag = array_pop ( $last_tag_history );
806
807 if ( !array_pop ( $has_opened_tr ) ) {
808 $line = "<tr><td></td></tr>{$line}";
809 }
810
811 if ( array_pop ( $tr_history ) ) {
812 $line = "</tr>{$line}";
813 }
814
815 if ( array_pop ( $td_history ) ) {
816 $line = "</{$last_tag}>{$line}";
817 }
818 array_pop ( $tr_attributes );
819 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
820 } else if ( substr ( $line , 0 , 2 ) === '|-' ) {
821 // Now we have a table row
822 $line = preg_replace( '#^\|-+#', '', $line );
823
824 // Whats after the tag is now only attributes
825 $attributes = $this->mStripState->unstripBoth( $line );
826 $attributes = Sanitizer::fixTagAttributes ( $attributes , 'tr' );
827 array_pop ( $tr_attributes );
828 array_push ( $tr_attributes , $attributes );
829
830 $line = '';
831 $last_tag = array_pop ( $last_tag_history );
832 array_pop ( $has_opened_tr );
833 array_push ( $has_opened_tr , true );
834
835 if ( array_pop ( $tr_history ) ) {
836 $line = '</tr>';
837 }
838
839 if ( array_pop ( $td_history ) ) {
840 $line = "</{$last_tag}>{$line}";
841 }
842
843 $outLine = $line;
844 array_push ( $tr_history , false );
845 array_push ( $td_history , false );
846 array_push ( $last_tag_history , '' );
847 }
848 else if ( $first_character === '|' || $first_character === '!' || substr ( $line , 0 , 2 ) === '|+' ) {
849 // This might be cell elements, td, th or captions
850 if ( substr ( $line , 0 , 2 ) === '|+' ) {
851 $first_character = '+';
852 $line = substr ( $line , 1 );
853 }
854
855 $line = substr ( $line , 1 );
856
857 if ( $first_character === '!' ) {
858 $line = str_replace ( '!!' , '||' , $line );
859 }
860
861 // Split up multiple cells on the same line.
862 // FIXME : This can result in improper nesting of tags processed
863 // by earlier parser steps, but should avoid splitting up eg
864 // attribute values containing literal "||".
865 $cells = StringUtils::explodeMarkup( '||' , $line );
866
867 $outLine = '';
868
869 // Loop through each table cell
870 foreach ( $cells as $cell )
871 {
872 $previous = '';
873 if ( $first_character !== '+' )
874 {
875 $tr_after = array_pop ( $tr_attributes );
876 if ( !array_pop ( $tr_history ) ) {
877 $previous = "<tr{$tr_after}>\n";
878 }
879 array_push ( $tr_history , true );
880 array_push ( $tr_attributes , '' );
881 array_pop ( $has_opened_tr );
882 array_push ( $has_opened_tr , true );
883 }
884
885 $last_tag = array_pop ( $last_tag_history );
886
887 if ( array_pop ( $td_history ) ) {
888 $previous = "</{$last_tag}>{$previous}";
889 }
890
891 if ( $first_character === '|' ) {
892 $last_tag = 'td';
893 } else if ( $first_character === '!' ) {
894 $last_tag = 'th';
895 } else if ( $first_character === '+' ) {
896 $last_tag = 'caption';
897 } else {
898 $last_tag = '';
899 }
900
901 array_push ( $last_tag_history , $last_tag );
902
903 // A cell could contain both parameters and data
904 $cell_data = explode ( '|' , $cell , 2 );
905
906 // Bug 553: Note that a '|' inside an invalid link should not
907 // be mistaken as delimiting cell parameters
908 if ( strpos( $cell_data[0], '[[' ) !== false ) {
909 $cell = "{$previous}<{$last_tag}>{$cell}";
910 } else if ( count ( $cell_data ) == 1 )
911 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
912 else {
913 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
914 $attributes = Sanitizer::fixTagAttributes( $attributes , $last_tag );
915 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
916 }
917
918 $outLine .= $cell;
919 array_push ( $td_history , true );
920 }
921 }
922 $out .= $outLine . "\n";
923 }
924
925 // Closing open td, tr && table
926 while ( count ( $td_history ) > 0 )
927 {
928 if ( array_pop ( $td_history ) ) {
929 $out .= "</td>\n";
930 }
931 if ( array_pop ( $tr_history ) ) {
932 $out .= "</tr>\n";
933 }
934 if ( !array_pop ( $has_opened_tr ) ) {
935 $out .= "<tr><td></td></tr>\n" ;
936 }
937
938 $out .= "</table>\n";
939 }
940
941 // Remove trailing line-ending (b/c)
942 if ( substr( $out, -1 ) === "\n" ) {
943 $out = substr( $out, 0, -1 );
944 }
945
946 // special case: don't return empty table
947 if( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
948 $out = '';
949 }
950
951 wfProfileOut( __METHOD__ );
952
953 return $out;
954 }
955
956 /**
957 * Helper function for parse() that transforms wiki markup into
958 * HTML. Only called for $mOutputType == self::OT_HTML.
959 *
960 * @private
961 */
962 function internalParse( $text ) {
963 $isMain = true;
964 wfProfileIn( __METHOD__ );
965
966 # Hook to suspend the parser in this state
967 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) {
968 wfProfileOut( __METHOD__ );
969 return $text ;
970 }
971
972 $text = $this->replaceVariables( $text );
973 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks ) );
974 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState ) );
975
976 // Tables need to come after variable replacement for things to work
977 // properly; putting them before other transformations should keep
978 // exciting things like link expansions from showing up in surprising
979 // places.
980 $text = $this->doTableStuff( $text );
981
982 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
983
984 $text = $this->doDoubleUnderscore( $text );
985 $text = $this->doHeadings( $text );
986 if($this->mOptions->getUseDynamicDates()) {
987 $df = DateFormatter::getInstance();
988 $text = $df->reformat( $this->mOptions->getDateFormat(), $text );
989 }
990 $text = $this->doAllQuotes( $text );
991 $text = $this->replaceInternalLinks( $text );
992 $text = $this->replaceExternalLinks( $text );
993
994 # replaceInternalLinks may sometimes leave behind
995 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
996 $text = str_replace($this->mUniqPrefix."NOPARSE", "", $text);
997
998 $text = $this->doMagicLinks( $text );
999 $text = $this->formatHeadings( $text, $isMain );
1000
1001 wfProfileOut( __METHOD__ );
1002 return $text;
1003 }
1004
1005 /**
1006 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1007 * magic external links.
1008 *
1009 * DML
1010 * @private
1011 */
1012 function doMagicLinks( $text ) {
1013 wfProfileIn( __METHOD__ );
1014 $prots = $this->mUrlProtocols;
1015 $urlChar = self::EXT_LINK_URL_CLASS;
1016 $text = preg_replace_callback(
1017 '!(?: # Start cases
1018 (<a.*?</a>) | # m[1]: Skip link text
1019 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1020 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1021 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1022 ISBN\s+(\b # m[5]: ISBN, capture number
1023 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1024 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1025 [0-9Xx] # check digit
1026 \b)
1027 )!x', array( &$this, 'magicLinkCallback' ), $text );
1028 wfProfileOut( __METHOD__ );
1029 return $text;
1030 }
1031
1032 function magicLinkCallback( $m ) {
1033 if ( isset( $m[1] ) && strval( $m[1] ) !== '' ) {
1034 # Skip anchor
1035 return $m[0];
1036 } elseif ( isset( $m[2] ) && strval( $m[2] ) !== '' ) {
1037 # Skip HTML element
1038 return $m[0];
1039 } elseif ( isset( $m[3] ) && strval( $m[3] ) !== '' ) {
1040 # Free external link
1041 return $this->makeFreeExternalLink( $m[0] );
1042 } elseif ( isset( $m[4] ) && strval( $m[4] ) !== '' ) {
1043 # RFC or PMID
1044 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1045 $keyword = 'RFC';
1046 $urlmsg = 'rfcurl';
1047 $id = $m[4];
1048 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1049 $keyword = 'PMID';
1050 $urlmsg = 'pubmedurl';
1051 $id = $m[4];
1052 } else {
1053 throw new MWException( __METHOD__.': unrecognised match type "' .
1054 substr($m[0], 0, 20 ) . '"' );
1055 }
1056 $url = wfMsg( $urlmsg, $id);
1057 $sk = $this->mOptions->getSkin();
1058 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1059 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1060 } elseif ( isset( $m[5] ) && strval( $m[5] ) !== '' ) {
1061 # ISBN
1062 $isbn = $m[5];
1063 $num = strtr( $isbn, array(
1064 '-' => '',
1065 ' ' => '',
1066 'x' => 'X',
1067 ));
1068 $titleObj = SpecialPage::getTitleFor( 'Booksources', $num );
1069 return'<a href="' .
1070 $titleObj->escapeLocalUrl() .
1071 "\" class=\"internal\">ISBN $isbn</a>";
1072 } else {
1073 return $m[0];
1074 }
1075 }
1076
1077 /**
1078 * Make a free external link, given a user-supplied URL
1079 * @return HTML
1080 * @private
1081 */
1082 function makeFreeExternalLink( $url ) {
1083 global $wgContLang;
1084 wfProfileIn( __METHOD__ );
1085
1086 $sk = $this->mOptions->getSkin();
1087 $trail = '';
1088
1089 # The characters '<' and '>' (which were escaped by
1090 # removeHTMLtags()) should not be included in
1091 # URLs, per RFC 2396.
1092 $m2 = array();
1093 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1094 $trail = substr($url, $m2[0][1]) . $trail;
1095 $url = substr($url, 0, $m2[0][1]);
1096 }
1097
1098 # Move trailing punctuation to $trail
1099 $sep = ',;\.:!?';
1100 # If there is no left bracket, then consider right brackets fair game too
1101 if ( strpos( $url, '(' ) === false ) {
1102 $sep .= ')';
1103 }
1104
1105 $numSepChars = strspn( strrev( $url ), $sep );
1106 if ( $numSepChars ) {
1107 $trail = substr( $url, -$numSepChars ) . $trail;
1108 $url = substr( $url, 0, -$numSepChars );
1109 }
1110
1111 $url = Sanitizer::cleanUrl( $url );
1112
1113 # Is this an external image?
1114 $text = $this->maybeMakeExternalImage( $url );
1115 if ( $text === false ) {
1116 # Not an image, make a link
1117 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle->getNamespace() );
1118 # Register it in the output object...
1119 # Replace unnecessary URL escape codes with their equivalent characters
1120 $pasteurized = self::replaceUnusualEscapes( $url );
1121 $this->mOutput->addExternalLink( $pasteurized );
1122 }
1123 wfProfileOut( __METHOD__ );
1124 return $text . $trail;
1125 }
1126
1127
1128 /**
1129 * Parse headers and return html
1130 *
1131 * @private
1132 */
1133 function doHeadings( $text ) {
1134 wfProfileIn( __METHOD__ );
1135 for ( $i = 6; $i >= 1; --$i ) {
1136 $h = str_repeat( '=', $i );
1137 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1138 "<h$i>\\1</h$i>", $text );
1139 }
1140 wfProfileOut( __METHOD__ );
1141 return $text;
1142 }
1143
1144 /**
1145 * Replace single quotes with HTML markup
1146 * @private
1147 * @return string the altered text
1148 */
1149 function doAllQuotes( $text ) {
1150 wfProfileIn( __METHOD__ );
1151 $outtext = '';
1152 $lines = StringUtils::explode( "\n", $text );
1153 foreach ( $lines as $line ) {
1154 $outtext .= $this->doQuotes( $line ) . "\n";
1155 }
1156 $outtext = substr($outtext, 0,-1);
1157 wfProfileOut( __METHOD__ );
1158 return $outtext;
1159 }
1160
1161 /**
1162 * Helper function for doAllQuotes()
1163 */
1164 public function doQuotes( $text ) {
1165 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1166 if ( count( $arr ) == 1 )
1167 return $text;
1168 else
1169 {
1170 # First, do some preliminary work. This may shift some apostrophes from
1171 # being mark-up to being text. It also counts the number of occurrences
1172 # of bold and italics mark-ups.
1173 $i = 0;
1174 $numbold = 0;
1175 $numitalics = 0;
1176 foreach ( $arr as $r )
1177 {
1178 if ( ( $i % 2 ) == 1 )
1179 {
1180 # If there are ever four apostrophes, assume the first is supposed to
1181 # be text, and the remaining three constitute mark-up for bold text.
1182 if ( strlen( $arr[$i] ) == 4 )
1183 {
1184 $arr[$i-1] .= "'";
1185 $arr[$i] = "'''";
1186 }
1187 # If there are more than 5 apostrophes in a row, assume they're all
1188 # text except for the last 5.
1189 else if ( strlen( $arr[$i] ) > 5 )
1190 {
1191 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1192 $arr[$i] = "'''''";
1193 }
1194 # Count the number of occurrences of bold and italics mark-ups.
1195 # We are not counting sequences of five apostrophes.
1196 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++; }
1197 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++; }
1198 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++; $numbold++; }
1199 }
1200 $i++;
1201 }
1202
1203 # If there is an odd number of both bold and italics, it is likely
1204 # that one of the bold ones was meant to be an apostrophe followed
1205 # by italics. Which one we cannot know for certain, but it is more
1206 # likely to be one that has a single-letter word before it.
1207 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) )
1208 {
1209 $i = 0;
1210 $firstsingleletterword = -1;
1211 $firstmultiletterword = -1;
1212 $firstspace = -1;
1213 foreach ( $arr as $r )
1214 {
1215 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) )
1216 {
1217 $x1 = substr ($arr[$i-1], -1);
1218 $x2 = substr ($arr[$i-1], -2, 1);
1219 if ($x1 === ' ') {
1220 if ($firstspace == -1) $firstspace = $i;
1221 } else if ($x2 === ' ') {
1222 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1223 } else {
1224 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1225 }
1226 }
1227 $i++;
1228 }
1229
1230 # If there is a single-letter word, use it!
1231 if ($firstsingleletterword > -1)
1232 {
1233 $arr [ $firstsingleletterword ] = "''";
1234 $arr [ $firstsingleletterword-1 ] .= "'";
1235 }
1236 # If not, but there's a multi-letter word, use that one.
1237 else if ($firstmultiletterword > -1)
1238 {
1239 $arr [ $firstmultiletterword ] = "''";
1240 $arr [ $firstmultiletterword-1 ] .= "'";
1241 }
1242 # ... otherwise use the first one that has neither.
1243 # (notice that it is possible for all three to be -1 if, for example,
1244 # there is only one pentuple-apostrophe in the line)
1245 else if ($firstspace > -1)
1246 {
1247 $arr [ $firstspace ] = "''";
1248 $arr [ $firstspace-1 ] .= "'";
1249 }
1250 }
1251
1252 # Now let's actually convert our apostrophic mush to HTML!
1253 $output = '';
1254 $buffer = '';
1255 $state = '';
1256 $i = 0;
1257 foreach ($arr as $r)
1258 {
1259 if (($i % 2) == 0)
1260 {
1261 if ($state === 'both')
1262 $buffer .= $r;
1263 else
1264 $output .= $r;
1265 }
1266 else
1267 {
1268 if (strlen ($r) == 2)
1269 {
1270 if ($state === 'i')
1271 { $output .= '</i>'; $state = ''; }
1272 else if ($state === 'bi')
1273 { $output .= '</i>'; $state = 'b'; }
1274 else if ($state === 'ib')
1275 { $output .= '</b></i><b>'; $state = 'b'; }
1276 else if ($state === 'both')
1277 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1278 else # $state can be 'b' or ''
1279 { $output .= '<i>'; $state .= 'i'; }
1280 }
1281 else if (strlen ($r) == 3)
1282 {
1283 if ($state === 'b')
1284 { $output .= '</b>'; $state = ''; }
1285 else if ($state === 'bi')
1286 { $output .= '</i></b><i>'; $state = 'i'; }
1287 else if ($state === 'ib')
1288 { $output .= '</b>'; $state = 'i'; }
1289 else if ($state === 'both')
1290 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1291 else # $state can be 'i' or ''
1292 { $output .= '<b>'; $state .= 'b'; }
1293 }
1294 else if (strlen ($r) == 5)
1295 {
1296 if ($state === 'b')
1297 { $output .= '</b><i>'; $state = 'i'; }
1298 else if ($state === 'i')
1299 { $output .= '</i><b>'; $state = 'b'; }
1300 else if ($state === 'bi')
1301 { $output .= '</i></b>'; $state = ''; }
1302 else if ($state === 'ib')
1303 { $output .= '</b></i>'; $state = ''; }
1304 else if ($state === 'both')
1305 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1306 else # ($state == '')
1307 { $buffer = ''; $state = 'both'; }
1308 }
1309 }
1310 $i++;
1311 }
1312 # Now close all remaining tags. Notice that the order is important.
1313 if ($state === 'b' || $state === 'ib')
1314 $output .= '</b>';
1315 if ($state === 'i' || $state === 'bi' || $state === 'ib')
1316 $output .= '</i>';
1317 if ($state === 'bi')
1318 $output .= '</b>';
1319 # There might be lonely ''''', so make sure we have a buffer
1320 if ($state === 'both' && $buffer)
1321 $output .= '<b><i>'.$buffer.'</i></b>';
1322 return $output;
1323 }
1324 }
1325
1326 /**
1327 * Replace external links (REL)
1328 *
1329 * Note: this is all very hackish and the order of execution matters a lot.
1330 * Make sure to run maintenance/parserTests.php if you change this code.
1331 *
1332 * @private
1333 */
1334 function replaceExternalLinks( $text ) {
1335 global $wgContLang;
1336 wfProfileIn( __METHOD__ );
1337
1338 $sk = $this->mOptions->getSkin();
1339
1340 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1341 $s = array_shift( $bits );
1342
1343 $i = 0;
1344 while ( $i<count( $bits ) ) {
1345 $url = $bits[$i++];
1346 $protocol = $bits[$i++];
1347 $text = $bits[$i++];
1348 $trail = $bits[$i++];
1349
1350 # The characters '<' and '>' (which were escaped by
1351 # removeHTMLtags()) should not be included in
1352 # URLs, per RFC 2396.
1353 $m2 = array();
1354 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1355 $text = substr($url, $m2[0][1]) . ' ' . $text;
1356 $url = substr($url, 0, $m2[0][1]);
1357 }
1358
1359 # If the link text is an image URL, replace it with an <img> tag
1360 # This happened by accident in the original parser, but some people used it extensively
1361 $img = $this->maybeMakeExternalImage( $text );
1362 if ( $img !== false ) {
1363 $text = $img;
1364 }
1365
1366 $dtrail = '';
1367
1368 # Set linktype for CSS - if URL==text, link is essentially free
1369 $linktype = ($text === $url) ? 'free' : 'text';
1370
1371 # No link text, e.g. [http://domain.tld/some.link]
1372 if ( $text == '' ) {
1373 # Autonumber if allowed. See bug #5918
1374 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1375 $text = '[' . ++$this->mAutonumber . ']';
1376 $linktype = 'autonumber';
1377 } else {
1378 # Otherwise just use the URL
1379 $text = htmlspecialchars( $url );
1380 $linktype = 'free';
1381 }
1382 } else {
1383 # Have link text, e.g. [http://domain.tld/some.link text]s
1384 # Check for trail
1385 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1386 }
1387
1388 $text = $wgContLang->markNoConversion($text);
1389
1390 $url = Sanitizer::cleanUrl( $url );
1391
1392 # Use the encoded URL
1393 # This means that users can paste URLs directly into the text
1394 # Funny characters like &ouml; aren't valid in URLs anyway
1395 # This was changed in August 2004
1396 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle->getNamespace() ) . $dtrail . $trail;
1397
1398 # Register link in the output object.
1399 # Replace unnecessary URL escape codes with the referenced character
1400 # This prevents spammers from hiding links from the filters
1401 $pasteurized = self::replaceUnusualEscapes( $url );
1402 $this->mOutput->addExternalLink( $pasteurized );
1403 }
1404
1405 wfProfileOut( __METHOD__ );
1406 return $s;
1407 }
1408
1409 /**
1410 * Replace unusual URL escape codes with their equivalent characters
1411 * @param string
1412 * @return string
1413 * @static
1414 * @todo This can merge genuinely required bits in the path or query string,
1415 * breaking legit URLs. A proper fix would treat the various parts of
1416 * the URL differently; as a workaround, just use the output for
1417 * statistical records, not for actual linking/output.
1418 */
1419 static function replaceUnusualEscapes( $url ) {
1420 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1421 array( __CLASS__, 'replaceUnusualEscapesCallback' ), $url );
1422 }
1423
1424 /**
1425 * Callback function used in replaceUnusualEscapes().
1426 * Replaces unusual URL escape codes with their equivalent character
1427 * @static
1428 * @private
1429 */
1430 private static function replaceUnusualEscapesCallback( $matches ) {
1431 $char = urldecode( $matches[0] );
1432 $ord = ord( $char );
1433 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1434 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1435 // No, shouldn't be escaped
1436 return $char;
1437 } else {
1438 // Yes, leave it escaped
1439 return $matches[0];
1440 }
1441 }
1442
1443 /**
1444 * make an image if it's allowed, either through the global
1445 * option or through the exception
1446 * @private
1447 */
1448 function maybeMakeExternalImage( $url ) {
1449 $sk = $this->mOptions->getSkin();
1450 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1451 $imagesexception = !empty($imagesfrom);
1452 $text = false;
1453 if ( $this->mOptions->getAllowExternalImages()
1454 || ( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1455 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1456 # Image found
1457 $text = $sk->makeExternalImage( $url );
1458 }
1459 }
1460 return $text;
1461 }
1462
1463 /**
1464 * Process [[ ]] wikilinks
1465 * @return processed text
1466 *
1467 * @private
1468 */
1469 function replaceInternalLinks( $s ) {
1470 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) );
1471 return $s;
1472 }
1473
1474 /**
1475 * Process [[ ]] wikilinks (RIL)
1476 * @return LinkHolderArray
1477 *
1478 * @private
1479 */
1480 function replaceInternalLinks2( &$s ) {
1481 global $wgContLang;
1482
1483 wfProfileIn( __METHOD__ );
1484
1485 wfProfileIn( __METHOD__.'-setup' );
1486 static $tc = FALSE, $e1, $e1_img;
1487 # the % is needed to support urlencoded titles as well
1488 if ( !$tc ) {
1489 $tc = Title::legalChars() . '#%';
1490 # Match a link having the form [[namespace:link|alternate]]trail
1491 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1492 # Match cases where there is no "]]", which might still be images
1493 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1494 }
1495
1496 $sk = $this->mOptions->getSkin();
1497 $holders = new LinkHolderArray( $this );
1498
1499 #split the entire text string on occurences of [[
1500 $a = StringUtils::explode( '[[', ' ' . $s );
1501 #get the first element (all text up to first [[), and remove the space we added
1502 $s = $a->current();
1503 $a->next();
1504 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1505 $s = substr( $s, 1 );
1506
1507 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1508 $e2 = null;
1509 if ( $useLinkPrefixExtension ) {
1510 # Match the end of a line for a word that's not followed by whitespace,
1511 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1512 $e2 = wfMsgForContent( 'linkprefix' );
1513 }
1514
1515 if( is_null( $this->mTitle ) ) {
1516 wfProfileOut( __METHOD__.'-setup' );
1517 wfProfileOut( __METHOD__ );
1518 throw new MWException( __METHOD__.": \$this->mTitle is null\n" );
1519 }
1520 $nottalk = !$this->mTitle->isTalkPage();
1521
1522 if ( $useLinkPrefixExtension ) {
1523 $m = array();
1524 if ( preg_match( $e2, $s, $m ) ) {
1525 $first_prefix = $m[2];
1526 } else {
1527 $first_prefix = false;
1528 }
1529 } else {
1530 $prefix = '';
1531 }
1532
1533 if($wgContLang->hasVariants()) {
1534 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle->getPrefixedText());
1535 } else {
1536 $selflink = array($this->mTitle->getPrefixedText());
1537 }
1538 $useSubpages = $this->areSubpagesAllowed();
1539 wfProfileOut( __METHOD__.'-setup' );
1540
1541 # Loop for each link
1542 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1543 # Check for excessive memory usage
1544 if ( $holders->isBig() ) {
1545 # Too big
1546 # Do the existence check, replace the link holders and clear the array
1547 $holders->replace( $s );
1548 $holders->clear();
1549 }
1550
1551 if ( $useLinkPrefixExtension ) {
1552 wfProfileIn( __METHOD__.'-prefixhandling' );
1553 if ( preg_match( $e2, $s, $m ) ) {
1554 $prefix = $m[2];
1555 $s = $m[1];
1556 } else {
1557 $prefix='';
1558 }
1559 # first link
1560 if($first_prefix) {
1561 $prefix = $first_prefix;
1562 $first_prefix = false;
1563 }
1564 wfProfileOut( __METHOD__.'-prefixhandling' );
1565 }
1566
1567 $might_be_img = false;
1568
1569 wfProfileIn( __METHOD__."-e1" );
1570 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1571 $text = $m[2];
1572 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1573 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1574 # the real problem is with the $e1 regex
1575 # See bug 1300.
1576 #
1577 # Still some problems for cases where the ] is meant to be outside punctuation,
1578 # and no image is in sight. See bug 2095.
1579 #
1580 if( $text !== '' &&
1581 substr( $m[3], 0, 1 ) === ']' &&
1582 strpos($text, '[') !== false
1583 )
1584 {
1585 $text .= ']'; # so that replaceExternalLinks($text) works later
1586 $m[3] = substr( $m[3], 1 );
1587 }
1588 # fix up urlencoded title texts
1589 if( strpos( $m[1], '%' ) !== false ) {
1590 # Should anchors '#' also be rejected?
1591 $m[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($m[1]) );
1592 }
1593 $trail = $m[3];
1594 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1595 $might_be_img = true;
1596 $text = $m[2];
1597 if ( strpos( $m[1], '%' ) !== false ) {
1598 $m[1] = urldecode($m[1]);
1599 }
1600 $trail = "";
1601 } else { # Invalid form; output directly
1602 $s .= $prefix . '[[' . $line ;
1603 wfProfileOut( __METHOD__."-e1" );
1604 continue;
1605 }
1606 wfProfileOut( __METHOD__."-e1" );
1607 wfProfileIn( __METHOD__."-misc" );
1608
1609 # Don't allow internal links to pages containing
1610 # PROTO: where PROTO is a valid URL protocol; these
1611 # should be external links.
1612 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1613 $s .= $prefix . '[[' . $line ;
1614 wfProfileOut( __METHOD__."-misc" );
1615 continue;
1616 }
1617
1618 # Make subpage if necessary
1619 if( $useSubpages ) {
1620 $link = $this->maybeDoSubpageLink( $m[1], $text );
1621 } else {
1622 $link = $m[1];
1623 }
1624
1625 $noforce = (substr($m[1], 0, 1) !== ':');
1626 if (!$noforce) {
1627 # Strip off leading ':'
1628 $link = substr($link, 1);
1629 }
1630
1631 wfProfileOut( __METHOD__."-misc" );
1632 wfProfileIn( __METHOD__."-title" );
1633 $nt = Title::newFromText( $this->mStripState->unstripNoWiki($link) );
1634 if( !$nt ) {
1635 $s .= $prefix . '[[' . $line;
1636 wfProfileOut( __METHOD__."-title" );
1637 continue;
1638 }
1639
1640 $ns = $nt->getNamespace();
1641 $iw = $nt->getInterWiki();
1642 wfProfileOut( __METHOD__."-title" );
1643
1644 if ($might_be_img) { # if this is actually an invalid link
1645 wfProfileIn( __METHOD__."-might_be_img" );
1646 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1647 $found = false;
1648 while ( true ) {
1649 #look at the next 'line' to see if we can close it there
1650 $a->next();
1651 $next_line = $a->current();
1652 if ( $next_line === false || $next_line === null ) {
1653 break;
1654 }
1655 $m = explode( ']]', $next_line, 3 );
1656 if ( count( $m ) == 3 ) {
1657 # the first ]] closes the inner link, the second the image
1658 $found = true;
1659 $text .= "[[{$m[0]}]]{$m[1]}";
1660 $trail = $m[2];
1661 break;
1662 } elseif ( count( $m ) == 2 ) {
1663 #if there's exactly one ]] that's fine, we'll keep looking
1664 $text .= "[[{$m[0]}]]{$m[1]}";
1665 } else {
1666 #if $next_line is invalid too, we need look no further
1667 $text .= '[[' . $next_line;
1668 break;
1669 }
1670 }
1671 if ( !$found ) {
1672 # we couldn't find the end of this imageLink, so output it raw
1673 #but don't ignore what might be perfectly normal links in the text we've examined
1674 $holders->merge( $this->replaceInternalLinks2( $text ) );
1675 $s .= "{$prefix}[[$link|$text";
1676 # note: no $trail, because without an end, there *is* no trail
1677 wfProfileOut( __METHOD__."-might_be_img" );
1678 continue;
1679 }
1680 } else { #it's not an image, so output it raw
1681 $s .= "{$prefix}[[$link|$text";
1682 # note: no $trail, because without an end, there *is* no trail
1683 wfProfileOut( __METHOD__."-might_be_img" );
1684 continue;
1685 }
1686 wfProfileOut( __METHOD__."-might_be_img" );
1687 }
1688
1689 $wasblank = ( '' == $text );
1690 if( $wasblank ) $text = $link;
1691
1692 # Link not escaped by : , create the various objects
1693 if( $noforce ) {
1694
1695 # Interwikis
1696 wfProfileIn( __METHOD__."-interwiki" );
1697 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1698 $this->mOutput->addLanguageLink( $nt->getFullText() );
1699 $s = rtrim($s . $prefix);
1700 $s .= trim($trail, "\n") == '' ? '': $prefix . $trail;
1701 wfProfileOut( __METHOD__."-interwiki" );
1702 continue;
1703 }
1704 wfProfileOut( __METHOD__."-interwiki" );
1705
1706 if ( $ns == NS_IMAGE ) {
1707 wfProfileIn( __METHOD__."-image" );
1708 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
1709 # recursively parse links inside the image caption
1710 # actually, this will parse them in any other parameters, too,
1711 # but it might be hard to fix that, and it doesn't matter ATM
1712 $text = $this->replaceExternalLinks($text);
1713 $holders->merge( $this->replaceInternalLinks2( $text ) );
1714
1715 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1716 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1717 }
1718 $this->mOutput->addImage( $nt->getDBkey() );
1719 wfProfileOut( __METHOD__."-image" );
1720 continue;
1721
1722 }
1723
1724 if ( $ns == NS_CATEGORY ) {
1725 wfProfileIn( __METHOD__."-category" );
1726 $s = rtrim($s . "\n"); # bug 87
1727
1728 if ( $wasblank ) {
1729 $sortkey = $this->getDefaultSort();
1730 } else {
1731 $sortkey = $text;
1732 }
1733 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
1734 $sortkey = str_replace( "\n", '', $sortkey );
1735 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1736 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
1737
1738 /**
1739 * Strip the whitespace Category links produce, see bug 87
1740 * @todo We might want to use trim($tmp, "\n") here.
1741 */
1742 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1743
1744 wfProfileOut( __METHOD__."-category" );
1745 continue;
1746 }
1747 }
1748
1749 # Self-link checking
1750 if( $nt->getFragment() === '' && $nt->getNamespace() != NS_SPECIAL ) {
1751 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1752 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1753 continue;
1754 }
1755 }
1756
1757 # Special and Media are pseudo-namespaces; no pages actually exist in them
1758 if( $ns == NS_MEDIA ) {
1759 # Give extensions a chance to select the file revision for us
1760 $skip = $time = false;
1761 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1762 if ( $skip ) {
1763 $link = $sk->link( $nt );
1764 } else {
1765 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1766 }
1767 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1768 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1769 $this->mOutput->addImage( $nt->getDBkey() );
1770 continue;
1771 } elseif( $ns == NS_SPECIAL ) {
1772 if( SpecialPage::exists( $nt->getDBkey() ) ) {
1773 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1774 } else {
1775 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1776 }
1777 continue;
1778 } elseif( $ns == NS_IMAGE ) {
1779 $img = wfFindFile( $nt );
1780 if( $img ) {
1781 // Force a blue link if the file exists; may be a remote
1782 // upload on the shared repository, and we want to see its
1783 // auto-generated page.
1784 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1785 $this->mOutput->addLink( $nt );
1786 continue;
1787 }
1788 }
1789 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1790 }
1791 wfProfileOut( __METHOD__ );
1792 return $holders;
1793 }
1794
1795 /**
1796 * Make a link placeholder. The text returned can be later resolved to a real link with
1797 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1798 * parsing of interwiki links, and secondly to allow all existence checks and
1799 * article length checks (for stub links) to be bundled into a single query.
1800 *
1801 * @deprecated
1802 */
1803 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1804 return $this->mLinkHolders->makeHolder( $nt, $text, $query, $trail, $prefix );
1805 }
1806
1807 /**
1808 * Render a forced-blue link inline; protect against double expansion of
1809 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1810 * Since this little disaster has to split off the trail text to avoid
1811 * breaking URLs in the following text without breaking trails on the
1812 * wiki links, it's been made into a horrible function.
1813 *
1814 * @param Title $nt
1815 * @param string $text
1816 * @param string $query
1817 * @param string $trail
1818 * @param string $prefix
1819 * @return string HTML-wikitext mix oh yuck
1820 */
1821 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1822 list( $inside, $trail ) = Linker::splitTrail( $trail );
1823 $sk = $this->mOptions->getSkin();
1824 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1825 return $this->armorLinks( $link ) . $trail;
1826 }
1827
1828 /**
1829 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1830 * going to go through further parsing steps before inline URL expansion.
1831 *
1832 * Not needed quite as much as it used to be since free links are a bit
1833 * more sensible these days. But bracketed links are still an issue.
1834 *
1835 * @param string more-or-less HTML
1836 * @return string less-or-more HTML with NOPARSE bits
1837 */
1838 function armorLinks( $text ) {
1839 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1840 "{$this->mUniqPrefix}NOPARSE$1", $text );
1841 }
1842
1843 /**
1844 * Return true if subpage links should be expanded on this page.
1845 * @return bool
1846 */
1847 function areSubpagesAllowed() {
1848 # Some namespaces don't allow subpages
1849 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
1850 }
1851
1852 /**
1853 * Handle link to subpage if necessary
1854 * @param string $target the source of the link
1855 * @param string &$text the link text, modified as necessary
1856 * @return string the full name of the link
1857 * @private
1858 */
1859 function maybeDoSubpageLink($target, &$text) {
1860 # Valid link forms:
1861 # Foobar -- normal
1862 # :Foobar -- override special treatment of prefix (images, language links)
1863 # /Foobar -- convert to CurrentPage/Foobar
1864 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1865 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1866 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1867
1868 wfProfileIn( __METHOD__ );
1869 $ret = $target; # default return value is no change
1870
1871 # Some namespaces don't allow subpages,
1872 # so only perform processing if subpages are allowed
1873 if( $this->areSubpagesAllowed() ) {
1874 $hash = strpos( $target, '#' );
1875 if( $hash !== false ) {
1876 $suffix = substr( $target, $hash );
1877 $target = substr( $target, 0, $hash );
1878 } else {
1879 $suffix = '';
1880 }
1881 # bug 7425
1882 $target = trim( $target );
1883 # Look at the first character
1884 if( $target != '' && $target{0} === '/' ) {
1885 # / at end means we don't want the slash to be shown
1886 $m = array();
1887 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1888 if( $trailingSlashes ) {
1889 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1890 } else {
1891 $noslash = substr( $target, 1 );
1892 }
1893
1894 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash) . $suffix;
1895 if( '' === $text ) {
1896 $text = $target . $suffix;
1897 } # this might be changed for ugliness reasons
1898 } else {
1899 # check for .. subpage backlinks
1900 $dotdotcount = 0;
1901 $nodotdot = $target;
1902 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1903 ++$dotdotcount;
1904 $nodotdot = substr( $nodotdot, 3 );
1905 }
1906 if($dotdotcount > 0) {
1907 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1908 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1909 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1910 # / at the end means don't show full path
1911 if( substr( $nodotdot, -1, 1 ) === '/' ) {
1912 $nodotdot = substr( $nodotdot, 0, -1 );
1913 if( '' === $text ) {
1914 $text = $nodotdot . $suffix;
1915 }
1916 }
1917 $nodotdot = trim( $nodotdot );
1918 if( $nodotdot != '' ) {
1919 $ret .= '/' . $nodotdot;
1920 }
1921 $ret .= $suffix;
1922 }
1923 }
1924 }
1925 }
1926
1927 wfProfileOut( __METHOD__ );
1928 return $ret;
1929 }
1930
1931 /**#@+
1932 * Used by doBlockLevels()
1933 * @private
1934 */
1935 /* private */ function closeParagraph() {
1936 $result = '';
1937 if ( '' != $this->mLastSection ) {
1938 $result = '</' . $this->mLastSection . ">\n";
1939 }
1940 $this->mInPre = false;
1941 $this->mLastSection = '';
1942 return $result;
1943 }
1944 # getCommon() returns the length of the longest common substring
1945 # of both arguments, starting at the beginning of both.
1946 #
1947 /* private */ function getCommon( $st1, $st2 ) {
1948 $fl = strlen( $st1 );
1949 $shorter = strlen( $st2 );
1950 if ( $fl < $shorter ) { $shorter = $fl; }
1951
1952 for ( $i = 0; $i < $shorter; ++$i ) {
1953 if ( $st1{$i} != $st2{$i} ) { break; }
1954 }
1955 return $i;
1956 }
1957 # These next three functions open, continue, and close the list
1958 # element appropriate to the prefix character passed into them.
1959 #
1960 /* private */ function openList( $char ) {
1961 $result = $this->closeParagraph();
1962
1963 if ( '*' === $char ) { $result .= '<ul><li>'; }
1964 else if ( '#' === $char ) { $result .= '<ol><li>'; }
1965 else if ( ':' === $char ) { $result .= '<dl><dd>'; }
1966 else if ( ';' === $char ) {
1967 $result .= '<dl><dt>';
1968 $this->mDTopen = true;
1969 }
1970 else { $result = '<!-- ERR 1 -->'; }
1971
1972 return $result;
1973 }
1974
1975 /* private */ function nextItem( $char ) {
1976 if ( '*' === $char || '#' === $char ) { return '</li><li>'; }
1977 else if ( ':' === $char || ';' === $char ) {
1978 $close = '</dd>';
1979 if ( $this->mDTopen ) { $close = '</dt>'; }
1980 if ( ';' === $char ) {
1981 $this->mDTopen = true;
1982 return $close . '<dt>';
1983 } else {
1984 $this->mDTopen = false;
1985 return $close . '<dd>';
1986 }
1987 }
1988 return '<!-- ERR 2 -->';
1989 }
1990
1991 /* private */ function closeList( $char ) {
1992 if ( '*' === $char ) { $text = '</li></ul>'; }
1993 else if ( '#' === $char ) { $text = '</li></ol>'; }
1994 else if ( ':' === $char ) {
1995 if ( $this->mDTopen ) {
1996 $this->mDTopen = false;
1997 $text = '</dt></dl>';
1998 } else {
1999 $text = '</dd></dl>';
2000 }
2001 }
2002 else { return '<!-- ERR 3 -->'; }
2003 return $text."\n";
2004 }
2005 /**#@-*/
2006
2007 /**
2008 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2009 *
2010 * @private
2011 * @return string the lists rendered as HTML
2012 */
2013 function doBlockLevels( $text, $linestart ) {
2014 wfProfileIn( __METHOD__ );
2015
2016 # Parsing through the text line by line. The main thing
2017 # happening here is handling of block-level elements p, pre,
2018 # and making lists from lines starting with * # : etc.
2019 #
2020 $textLines = StringUtils::explode( "\n", $text );
2021
2022 $lastPrefix = $output = '';
2023 $this->mDTopen = $inBlockElem = false;
2024 $prefixLength = 0;
2025 $paragraphStack = false;
2026
2027 foreach ( $textLines as $oLine ) {
2028 # Fix up $linestart
2029 if ( !$linestart ) {
2030 $output .= $oLine;
2031 $linestart = true;
2032 continue;
2033 }
2034
2035 $lastPrefixLength = strlen( $lastPrefix );
2036 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2037 $preOpenMatch = preg_match('/<pre/i', $oLine );
2038 if ( !$this->mInPre ) {
2039 # Multiple prefixes may abut each other for nested lists.
2040 $prefixLength = strspn( $oLine, '*#:;' );
2041 $prefix = substr( $oLine, 0, $prefixLength );
2042
2043 # eh?
2044 $prefix2 = str_replace( ';', ':', $prefix );
2045 $t = substr( $oLine, $prefixLength );
2046 $this->mInPre = (bool)$preOpenMatch;
2047 } else {
2048 # Don't interpret any other prefixes in preformatted text
2049 $prefixLength = 0;
2050 $prefix = $prefix2 = '';
2051 $t = $oLine;
2052 }
2053
2054 # List generation
2055 if( $prefixLength && $lastPrefix === $prefix2 ) {
2056 # Same as the last item, so no need to deal with nesting or opening stuff
2057 $output .= $this->nextItem( substr( $prefix, -1 ) );
2058 $paragraphStack = false;
2059
2060 if ( substr( $prefix, -1 ) === ';') {
2061 # The one nasty exception: definition lists work like this:
2062 # ; title : definition text
2063 # So we check for : in the remainder text to split up the
2064 # title and definition, without b0rking links.
2065 $term = $t2 = '';
2066 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2067 $t = $t2;
2068 $output .= $term . $this->nextItem( ':' );
2069 }
2070 }
2071 } elseif( $prefixLength || $lastPrefixLength ) {
2072 # Either open or close a level...
2073 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2074 $paragraphStack = false;
2075
2076 while( $commonPrefixLength < $lastPrefixLength ) {
2077 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2078 --$lastPrefixLength;
2079 }
2080 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2081 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2082 }
2083 while ( $prefixLength > $commonPrefixLength ) {
2084 $char = substr( $prefix, $commonPrefixLength, 1 );
2085 $output .= $this->openList( $char );
2086
2087 if ( ';' === $char ) {
2088 # FIXME: This is dupe of code above
2089 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2090 $t = $t2;
2091 $output .= $term . $this->nextItem( ':' );
2092 }
2093 }
2094 ++$commonPrefixLength;
2095 }
2096 $lastPrefix = $prefix2;
2097 }
2098 if( 0 == $prefixLength ) {
2099 wfProfileIn( __METHOD__."-paragraph" );
2100 # No prefix (not in list)--go to paragraph mode
2101 // XXX: use a stack for nestable elements like span, table and div
2102 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2103 $closematch = preg_match(
2104 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2105 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2106 if ( $openmatch or $closematch ) {
2107 $paragraphStack = false;
2108 # TODO bug 5718: paragraph closed
2109 $output .= $this->closeParagraph();
2110 if ( $preOpenMatch and !$preCloseMatch ) {
2111 $this->mInPre = true;
2112 }
2113 if ( $closematch ) {
2114 $inBlockElem = false;
2115 } else {
2116 $inBlockElem = true;
2117 }
2118 } else if ( !$inBlockElem && !$this->mInPre ) {
2119 if ( ' ' == $t{0} and ( $this->mLastSection === 'pre' or trim($t) != '' ) ) {
2120 // pre
2121 if ($this->mLastSection !== 'pre') {
2122 $paragraphStack = false;
2123 $output .= $this->closeParagraph().'<pre>';
2124 $this->mLastSection = 'pre';
2125 }
2126 $t = substr( $t, 1 );
2127 } else {
2128 // paragraph
2129 if ( '' == trim($t) ) {
2130 if ( $paragraphStack ) {
2131 $output .= $paragraphStack.'<br />';
2132 $paragraphStack = false;
2133 $this->mLastSection = 'p';
2134 } else {
2135 if ($this->mLastSection !== 'p' ) {
2136 $output .= $this->closeParagraph();
2137 $this->mLastSection = '';
2138 $paragraphStack = '<p>';
2139 } else {
2140 $paragraphStack = '</p><p>';
2141 }
2142 }
2143 } else {
2144 if ( $paragraphStack ) {
2145 $output .= $paragraphStack;
2146 $paragraphStack = false;
2147 $this->mLastSection = 'p';
2148 } else if ($this->mLastSection !== 'p') {
2149 $output .= $this->closeParagraph().'<p>';
2150 $this->mLastSection = 'p';
2151 }
2152 }
2153 }
2154 }
2155 wfProfileOut( __METHOD__."-paragraph" );
2156 }
2157 // somewhere above we forget to get out of pre block (bug 785)
2158 if($preCloseMatch && $this->mInPre) {
2159 $this->mInPre = false;
2160 }
2161 if ($paragraphStack === false) {
2162 $output .= $t."\n";
2163 }
2164 }
2165 while ( $prefixLength ) {
2166 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2167 --$prefixLength;
2168 }
2169 if ( '' != $this->mLastSection ) {
2170 $output .= '</' . $this->mLastSection . '>';
2171 $this->mLastSection = '';
2172 }
2173
2174 wfProfileOut( __METHOD__ );
2175 return $output;
2176 }
2177
2178 /**
2179 * Split up a string on ':', ignoring any occurences inside tags
2180 * to prevent illegal overlapping.
2181 * @param string $str the string to split
2182 * @param string &$before set to everything before the ':'
2183 * @param string &$after set to everything after the ':'
2184 * return string the position of the ':', or false if none found
2185 */
2186 function findColonNoLinks($str, &$before, &$after) {
2187 wfProfileIn( __METHOD__ );
2188
2189 $pos = strpos( $str, ':' );
2190 if( $pos === false ) {
2191 // Nothing to find!
2192 wfProfileOut( __METHOD__ );
2193 return false;
2194 }
2195
2196 $lt = strpos( $str, '<' );
2197 if( $lt === false || $lt > $pos ) {
2198 // Easy; no tag nesting to worry about
2199 $before = substr( $str, 0, $pos );
2200 $after = substr( $str, $pos+1 );
2201 wfProfileOut( __METHOD__ );
2202 return $pos;
2203 }
2204
2205 // Ugly state machine to walk through avoiding tags.
2206 $state = self::COLON_STATE_TEXT;
2207 $stack = 0;
2208 $len = strlen( $str );
2209 for( $i = 0; $i < $len; $i++ ) {
2210 $c = $str{$i};
2211
2212 switch( $state ) {
2213 // (Using the number is a performance hack for common cases)
2214 case 0: // self::COLON_STATE_TEXT:
2215 switch( $c ) {
2216 case "<":
2217 // Could be either a <start> tag or an </end> tag
2218 $state = self::COLON_STATE_TAGSTART;
2219 break;
2220 case ":":
2221 if( $stack == 0 ) {
2222 // We found it!
2223 $before = substr( $str, 0, $i );
2224 $after = substr( $str, $i + 1 );
2225 wfProfileOut( __METHOD__ );
2226 return $i;
2227 }
2228 // Embedded in a tag; don't break it.
2229 break;
2230 default:
2231 // Skip ahead looking for something interesting
2232 $colon = strpos( $str, ':', $i );
2233 if( $colon === false ) {
2234 // Nothing else interesting
2235 wfProfileOut( __METHOD__ );
2236 return false;
2237 }
2238 $lt = strpos( $str, '<', $i );
2239 if( $stack === 0 ) {
2240 if( $lt === false || $colon < $lt ) {
2241 // We found it!
2242 $before = substr( $str, 0, $colon );
2243 $after = substr( $str, $colon + 1 );
2244 wfProfileOut( __METHOD__ );
2245 return $i;
2246 }
2247 }
2248 if( $lt === false ) {
2249 // Nothing else interesting to find; abort!
2250 // We're nested, but there's no close tags left. Abort!
2251 break 2;
2252 }
2253 // Skip ahead to next tag start
2254 $i = $lt;
2255 $state = self::COLON_STATE_TAGSTART;
2256 }
2257 break;
2258 case 1: // self::COLON_STATE_TAG:
2259 // In a <tag>
2260 switch( $c ) {
2261 case ">":
2262 $stack++;
2263 $state = self::COLON_STATE_TEXT;
2264 break;
2265 case "/":
2266 // Slash may be followed by >?
2267 $state = self::COLON_STATE_TAGSLASH;
2268 break;
2269 default:
2270 // ignore
2271 }
2272 break;
2273 case 2: // self::COLON_STATE_TAGSTART:
2274 switch( $c ) {
2275 case "/":
2276 $state = self::COLON_STATE_CLOSETAG;
2277 break;
2278 case "!":
2279 $state = self::COLON_STATE_COMMENT;
2280 break;
2281 case ">":
2282 // Illegal early close? This shouldn't happen D:
2283 $state = self::COLON_STATE_TEXT;
2284 break;
2285 default:
2286 $state = self::COLON_STATE_TAG;
2287 }
2288 break;
2289 case 3: // self::COLON_STATE_CLOSETAG:
2290 // In a </tag>
2291 if( $c === ">" ) {
2292 $stack--;
2293 if( $stack < 0 ) {
2294 wfDebug( __METHOD__.": Invalid input; too many close tags\n" );
2295 wfProfileOut( __METHOD__ );
2296 return false;
2297 }
2298 $state = self::COLON_STATE_TEXT;
2299 }
2300 break;
2301 case self::COLON_STATE_TAGSLASH:
2302 if( $c === ">" ) {
2303 // Yes, a self-closed tag <blah/>
2304 $state = self::COLON_STATE_TEXT;
2305 } else {
2306 // Probably we're jumping the gun, and this is an attribute
2307 $state = self::COLON_STATE_TAG;
2308 }
2309 break;
2310 case 5: // self::COLON_STATE_COMMENT:
2311 if( $c === "-" ) {
2312 $state = self::COLON_STATE_COMMENTDASH;
2313 }
2314 break;
2315 case self::COLON_STATE_COMMENTDASH:
2316 if( $c === "-" ) {
2317 $state = self::COLON_STATE_COMMENTDASHDASH;
2318 } else {
2319 $state = self::COLON_STATE_COMMENT;
2320 }
2321 break;
2322 case self::COLON_STATE_COMMENTDASHDASH:
2323 if( $c === ">" ) {
2324 $state = self::COLON_STATE_TEXT;
2325 } else {
2326 $state = self::COLON_STATE_COMMENT;
2327 }
2328 break;
2329 default:
2330 throw new MWException( "State machine error in " . __METHOD__ );
2331 }
2332 }
2333 if( $stack > 0 ) {
2334 wfDebug( __METHOD__.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2335 return false;
2336 }
2337 wfProfileOut( __METHOD__ );
2338 return false;
2339 }
2340
2341 /**
2342 * Return value of a magic variable (like PAGENAME)
2343 *
2344 * @private
2345 */
2346 function getVariableValue( $index ) {
2347 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2348
2349 /**
2350 * Some of these require message or data lookups and can be
2351 * expensive to check many times.
2352 */
2353 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) {
2354 if ( isset( $this->mVarCache[$index] ) ) {
2355 return $this->mVarCache[$index];
2356 }
2357 }
2358
2359 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2360 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2361
2362 # Use the time zone
2363 global $wgLocaltimezone;
2364 if ( isset( $wgLocaltimezone ) ) {
2365 $oldtz = getenv( 'TZ' );
2366 putenv( 'TZ='.$wgLocaltimezone );
2367 }
2368
2369 wfSuppressWarnings(); // E_STRICT system time bitching
2370 $localTimestamp = date( 'YmdHis', $ts );
2371 $localMonth = date( 'm', $ts );
2372 $localMonthName = date( 'n', $ts );
2373 $localDay = date( 'j', $ts );
2374 $localDay2 = date( 'd', $ts );
2375 $localDayOfWeek = date( 'w', $ts );
2376 $localWeek = date( 'W', $ts );
2377 $localYear = date( 'Y', $ts );
2378 $localHour = date( 'H', $ts );
2379 if ( isset( $wgLocaltimezone ) ) {
2380 putenv( 'TZ='.$oldtz );
2381 }
2382 wfRestoreWarnings();
2383
2384 switch ( $index ) {
2385 case 'currentmonth':
2386 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2387 case 'currentmonthname':
2388 return $this->mVarCache[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2389 case 'currentmonthnamegen':
2390 return $this->mVarCache[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2391 case 'currentmonthabbrev':
2392 return $this->mVarCache[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2393 case 'currentday':
2394 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2395 case 'currentday2':
2396 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2397 case 'localmonth':
2398 return $this->mVarCache[$index] = $wgContLang->formatNum( $localMonth );
2399 case 'localmonthname':
2400 return $this->mVarCache[$index] = $wgContLang->getMonthName( $localMonthName );
2401 case 'localmonthnamegen':
2402 return $this->mVarCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2403 case 'localmonthabbrev':
2404 return $this->mVarCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2405 case 'localday':
2406 return $this->mVarCache[$index] = $wgContLang->formatNum( $localDay );
2407 case 'localday2':
2408 return $this->mVarCache[$index] = $wgContLang->formatNum( $localDay2 );
2409 case 'pagename':
2410 return wfEscapeWikiText( $this->mTitle->getText() );
2411 case 'pagenamee':
2412 return $this->mTitle->getPartialURL();
2413 case 'fullpagename':
2414 return wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2415 case 'fullpagenamee':
2416 return $this->mTitle->getPrefixedURL();
2417 case 'subpagename':
2418 return wfEscapeWikiText( $this->mTitle->getSubpageText() );
2419 case 'subpagenamee':
2420 return $this->mTitle->getSubpageUrlForm();
2421 case 'basepagename':
2422 return wfEscapeWikiText( $this->mTitle->getBaseText() );
2423 case 'basepagenamee':
2424 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) );
2425 case 'talkpagename':
2426 if( $this->mTitle->canTalk() ) {
2427 $talkPage = $this->mTitle->getTalkPage();
2428 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2429 } else {
2430 return '';
2431 }
2432 case 'talkpagenamee':
2433 if( $this->mTitle->canTalk() ) {
2434 $talkPage = $this->mTitle->getTalkPage();
2435 return $talkPage->getPrefixedUrl();
2436 } else {
2437 return '';
2438 }
2439 case 'subjectpagename':
2440 $subjPage = $this->mTitle->getSubjectPage();
2441 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2442 case 'subjectpagenamee':
2443 $subjPage = $this->mTitle->getSubjectPage();
2444 return $subjPage->getPrefixedUrl();
2445 case 'revisionid':
2446 // Let the edit saving system know we should parse the page
2447 // *after* a revision ID has been assigned.
2448 $this->mOutput->setFlag( 'vary-revision' );
2449 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" );
2450 return $this->mRevisionId;
2451 case 'revisionday':
2452 // Let the edit saving system know we should parse the page
2453 // *after* a revision ID has been assigned. This is for null edits.
2454 $this->mOutput->setFlag( 'vary-revision' );
2455 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2456 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2457 case 'revisionday2':
2458 // Let the edit saving system know we should parse the page
2459 // *after* a revision ID has been assigned. This is for null edits.
2460 $this->mOutput->setFlag( 'vary-revision' );
2461 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2462 return substr( $this->getRevisionTimestamp(), 6, 2 );
2463 case 'revisionmonth':
2464 // Let the edit saving system know we should parse the page
2465 // *after* a revision ID has been assigned. This is for null edits.
2466 $this->mOutput->setFlag( 'vary-revision' );
2467 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2468 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2469 case 'revisionyear':
2470 // Let the edit saving system know we should parse the page
2471 // *after* a revision ID has been assigned. This is for null edits.
2472 $this->mOutput->setFlag( 'vary-revision' );
2473 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2474 return substr( $this->getRevisionTimestamp(), 0, 4 );
2475 case 'revisiontimestamp':
2476 // Let the edit saving system know we should parse the page
2477 // *after* a revision ID has been assigned. This is for null edits.
2478 $this->mOutput->setFlag( 'vary-revision' );
2479 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2480 return $this->getRevisionTimestamp();
2481 case 'namespace':
2482 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2483 case 'namespacee':
2484 return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2485 case 'talkspace':
2486 return $this->mTitle->canTalk() ? str_replace('_',' ',$this->mTitle->getTalkNsText()) : '';
2487 case 'talkspacee':
2488 return $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2489 case 'subjectspace':
2490 return $this->mTitle->getSubjectNsText();
2491 case 'subjectspacee':
2492 return( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2493 case 'currentdayname':
2494 return $this->mVarCache[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) + 1 );
2495 case 'currentyear':
2496 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2497 case 'currenttime':
2498 return $this->mVarCache[$index] = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2499 case 'currenthour':
2500 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2501 case 'currentweek':
2502 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2503 // int to remove the padding
2504 return $this->mVarCache[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2505 case 'currentdow':
2506 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2507 case 'localdayname':
2508 return $this->mVarCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek + 1 );
2509 case 'localyear':
2510 return $this->mVarCache[$index] = $wgContLang->formatNum( $localYear, true );
2511 case 'localtime':
2512 return $this->mVarCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2513 case 'localhour':
2514 return $this->mVarCache[$index] = $wgContLang->formatNum( $localHour, true );
2515 case 'localweek':
2516 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2517 // int to remove the padding
2518 return $this->mVarCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2519 case 'localdow':
2520 return $this->mVarCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2521 case 'numberofarticles':
2522 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::articles() );
2523 case 'numberoffiles':
2524 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::images() );
2525 case 'numberofusers':
2526 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::users() );
2527 case 'numberofpages':
2528 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::pages() );
2529 case 'numberofadmins':
2530 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::numberingroup('sysop') );
2531 case 'numberofedits':
2532 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::edits() );
2533 case 'currenttimestamp':
2534 return $this->mVarCache[$index] = wfTimestamp( TS_MW, $ts );
2535 case 'localtimestamp':
2536 return $this->mVarCache[$index] = $localTimestamp;
2537 case 'currentversion':
2538 return $this->mVarCache[$index] = SpecialVersion::getVersion();
2539 case 'sitename':
2540 return $wgSitename;
2541 case 'server':
2542 return $wgServer;
2543 case 'servername':
2544 return $wgServerName;
2545 case 'scriptpath':
2546 return $wgScriptPath;
2547 case 'directionmark':
2548 return $wgContLang->getDirMark();
2549 case 'contentlanguage':
2550 global $wgContLanguageCode;
2551 return $wgContLanguageCode;
2552 default:
2553 $ret = null;
2554 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache, &$index, &$ret ) ) )
2555 return $ret;
2556 else
2557 return null;
2558 }
2559 }
2560
2561 /**
2562 * initialise the magic variables (like CURRENTMONTHNAME)
2563 *
2564 * @private
2565 */
2566 function initialiseVariables() {
2567 wfProfileIn( __METHOD__ );
2568 $variableIDs = MagicWord::getVariableIDs();
2569
2570 $this->mVariables = new MagicWordArray( $variableIDs );
2571 wfProfileOut( __METHOD__ );
2572 }
2573
2574 /**
2575 * Preprocess some wikitext and return the document tree.
2576 * This is the ghost of replace_variables().
2577 *
2578 * @param string $text The text to parse
2579 * @param integer flags Bitwise combination of:
2580 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2581 * included. Default is to assume a direct page view.
2582 *
2583 * The generated DOM tree must depend only on the input text and the flags.
2584 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2585 *
2586 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2587 * change in the DOM tree for a given text, must be passed through the section identifier
2588 * in the section edit link and thus back to extractSections().
2589 *
2590 * The output of this function is currently only cached in process memory, but a persistent
2591 * cache may be implemented at a later date which takes further advantage of these strict
2592 * dependency requirements.
2593 *
2594 * @private
2595 */
2596 function preprocessToDom ( $text, $flags = 0 ) {
2597 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2598 return $dom;
2599 }
2600
2601 /*
2602 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2603 */
2604 public static function splitWhitespace( $s ) {
2605 $ltrimmed = ltrim( $s );
2606 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2607 $trimmed = rtrim( $ltrimmed );
2608 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2609 if ( $diff > 0 ) {
2610 $w2 = substr( $ltrimmed, -$diff );
2611 } else {
2612 $w2 = '';
2613 }
2614 return array( $w1, $trimmed, $w2 );
2615 }
2616
2617 /**
2618 * Replace magic variables, templates, and template arguments
2619 * with the appropriate text. Templates are substituted recursively,
2620 * taking care to avoid infinite loops.
2621 *
2622 * Note that the substitution depends on value of $mOutputType:
2623 * self::OT_WIKI: only {{subst:}} templates
2624 * self::OT_PREPROCESS: templates but not extension tags
2625 * self::OT_HTML: all templates and extension tags
2626 *
2627 * @param string $tex The text to transform
2628 * @param PPFrame $frame Object describing the arguments passed to the template.
2629 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2630 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2631 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2632 * @private
2633 */
2634 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2635 # Prevent too big inclusions
2636 if( strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
2637 return $text;
2638 }
2639
2640 wfProfileIn( __METHOD__ );
2641
2642 if ( $frame === false ) {
2643 $frame = $this->getPreprocessor()->newFrame();
2644 } elseif ( !( $frame instanceof PPFrame ) ) {
2645 wfDebug( __METHOD__." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2646 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2647 }
2648
2649 $dom = $this->preprocessToDom( $text );
2650 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
2651 $text = $frame->expand( $dom, $flags );
2652
2653 wfProfileOut( __METHOD__ );
2654 return $text;
2655 }
2656
2657 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2658 static function createAssocArgs( $args ) {
2659 $assocArgs = array();
2660 $index = 1;
2661 foreach( $args as $arg ) {
2662 $eqpos = strpos( $arg, '=' );
2663 if ( $eqpos === false ) {
2664 $assocArgs[$index++] = $arg;
2665 } else {
2666 $name = trim( substr( $arg, 0, $eqpos ) );
2667 $value = trim( substr( $arg, $eqpos+1 ) );
2668 if ( $value === false ) {
2669 $value = '';
2670 }
2671 if ( $name !== false ) {
2672 $assocArgs[$name] = $value;
2673 }
2674 }
2675 }
2676
2677 return $assocArgs;
2678 }
2679
2680 /**
2681 * Warn the user when a parser limitation is reached
2682 * Will warn at most once the user per limitation type
2683 *
2684 * @param string $limitationType, should be one of:
2685 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2686 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2687 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2688 * @params int $current, $max When an explicit limit has been
2689 * exceeded, provide the values (optional)
2690 */
2691 function limitationWarn( $limitationType, $current=null, $max=null) {
2692 $msgName = $limitationType . '-warning';
2693 //does no harm if $current and $max are present but are unnecessary for the message
2694 $warning = wfMsgExt( $msgName, array( 'parsemag', 'escape' ), $current, $max );
2695 $this->mOutput->addWarning( $warning );
2696 $cat = Title::makeTitleSafe( NS_CATEGORY, wfMsgForContent( $limitationType . '-category' ) );
2697 if ( $cat ) {
2698 $this->mOutput->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2699 }
2700 }
2701
2702 /**
2703 * Return the text of a template, after recursively
2704 * replacing any variables or templates within the template.
2705 *
2706 * @param array $piece The parts of the template
2707 * $piece['title']: the title, i.e. the part before the |
2708 * $piece['parts']: the parameter array
2709 * $piece['lineStart']: whether the brace was at the start of a line
2710 * @param PPFrame The current frame, contains template arguments
2711 * @return string the text of the template
2712 * @private
2713 */
2714 function braceSubstitution( $piece, $frame ) {
2715 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2716 wfProfileIn( __METHOD__ );
2717 wfProfileIn( __METHOD__.'-setup' );
2718
2719 # Flags
2720 $found = false; # $text has been filled
2721 $nowiki = false; # wiki markup in $text should be escaped
2722 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2723 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2724 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2725 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2726
2727 # Title object, where $text came from
2728 $title = NULL;
2729
2730 # $part1 is the bit before the first |, and must contain only title characters.
2731 # Various prefixes will be stripped from it later.
2732 $titleWithSpaces = $frame->expand( $piece['title'] );
2733 $part1 = trim( $titleWithSpaces );
2734 $titleText = false;
2735
2736 # Original title text preserved for various purposes
2737 $originalTitle = $part1;
2738
2739 # $args is a list of argument nodes, starting from index 0, not including $part1
2740 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2741 wfProfileOut( __METHOD__.'-setup' );
2742
2743 # SUBST
2744 wfProfileIn( __METHOD__.'-modifiers' );
2745 if ( !$found ) {
2746 $mwSubst = MagicWord::get( 'subst' );
2747 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot['wiki'] ) {
2748 # One of two possibilities is true:
2749 # 1) Found SUBST but not in the PST phase
2750 # 2) Didn't find SUBST and in the PST phase
2751 # In either case, return without further processing
2752 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2753 $isLocalObj = true;
2754 $found = true;
2755 }
2756 }
2757
2758 # Variables
2759 if ( !$found && $args->getLength() == 0 ) {
2760 $id = $this->mVariables->matchStartToEnd( $part1 );
2761 if ( $id !== false ) {
2762 $text = $this->getVariableValue( $id );
2763 if (MagicWord::getCacheTTL($id)>-1)
2764 $this->mOutput->mContainsOldMagic = true;
2765 $found = true;
2766 }
2767 }
2768
2769 # MSG, MSGNW and RAW
2770 if ( !$found ) {
2771 # Check for MSGNW:
2772 $mwMsgnw = MagicWord::get( 'msgnw' );
2773 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2774 $nowiki = true;
2775 } else {
2776 # Remove obsolete MSG:
2777 $mwMsg = MagicWord::get( 'msg' );
2778 $mwMsg->matchStartAndRemove( $part1 );
2779 }
2780
2781 # Check for RAW:
2782 $mwRaw = MagicWord::get( 'raw' );
2783 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2784 $forceRawInterwiki = true;
2785 }
2786 }
2787 wfProfileOut( __METHOD__.'-modifiers' );
2788
2789 # Parser functions
2790 if ( !$found ) {
2791 wfProfileIn( __METHOD__ . '-pfunc' );
2792
2793 $colonPos = strpos( $part1, ':' );
2794 if ( $colonPos !== false ) {
2795 # Case sensitive functions
2796 $function = substr( $part1, 0, $colonPos );
2797 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
2798 $function = $this->mFunctionSynonyms[1][$function];
2799 } else {
2800 # Case insensitive functions
2801 $function = strtolower( $function );
2802 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
2803 $function = $this->mFunctionSynonyms[0][$function];
2804 } else {
2805 $function = false;
2806 }
2807 }
2808 if ( $function ) {
2809 list( $callback, $flags ) = $this->mFunctionHooks[$function];
2810 $initialArgs = array( &$this );
2811 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
2812 if ( $flags & SFH_OBJECT_ARGS ) {
2813 # Add a frame parameter, and pass the arguments as an array
2814 $allArgs = $initialArgs;
2815 $allArgs[] = $frame;
2816 for ( $i = 0; $i < $args->getLength(); $i++ ) {
2817 $funcArgs[] = $args->item( $i );
2818 }
2819 $allArgs[] = $funcArgs;
2820 } else {
2821 # Convert arguments to plain text
2822 for ( $i = 0; $i < $args->getLength(); $i++ ) {
2823 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2824 }
2825 $allArgs = array_merge( $initialArgs, $funcArgs );
2826 }
2827
2828 # Workaround for PHP bug 35229 and similar
2829 if ( !is_callable( $callback ) ) {
2830 throw new MWException( "Tag hook for $name is not callable\n" );
2831 }
2832 $result = call_user_func_array( $callback, $allArgs );
2833 $found = true;
2834 $noparse = true;
2835 $preprocessFlags = 0;
2836
2837 if ( is_array( $result ) ) {
2838 if ( isset( $result[0] ) ) {
2839 $text = $result[0];
2840 unset( $result[0] );
2841 }
2842
2843 // Extract flags into the local scope
2844 // This allows callers to set flags such as nowiki, found, etc.
2845 extract( $result );
2846 } else {
2847 $text = $result;
2848 }
2849 if ( !$noparse ) {
2850 $text = $this->preprocessToDom( $text, $preprocessFlags );
2851 $isChildObj = true;
2852 }
2853 }
2854 }
2855 wfProfileOut( __METHOD__ . '-pfunc' );
2856 }
2857
2858 # Finish mangling title and then check for loops.
2859 # Set $title to a Title object and $titleText to the PDBK
2860 if ( !$found ) {
2861 $ns = NS_TEMPLATE;
2862 # Split the title into page and subpage
2863 $subpage = '';
2864 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2865 if ($subpage !== '') {
2866 $ns = $this->mTitle->getNamespace();
2867 }
2868 $title = Title::newFromText( $part1, $ns );
2869 if ( $title ) {
2870 $titleText = $title->getPrefixedText();
2871 # Check for language variants if the template is not found
2872 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2873 $wgContLang->findVariantLink( $part1, $title, true );
2874 }
2875 # Do infinite loop check
2876 if ( !$frame->loopCheck( $title ) ) {
2877 $found = true;
2878 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2879 wfDebug( __METHOD__.": template loop broken at '$titleText'\n" );
2880 }
2881 # Do recursion depth check
2882 $limit = $this->mOptions->getMaxTemplateDepth();
2883 if ( $frame->depth >= $limit ) {
2884 $found = true;
2885 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2886 }
2887 }
2888 }
2889
2890 # Load from database
2891 if ( !$found && $title ) {
2892 wfProfileIn( __METHOD__ . '-loadtpl' );
2893 if ( !$title->isExternal() ) {
2894 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() && $this->ot['html'] ) {
2895 $text = SpecialPage::capturePath( $title );
2896 if ( is_string( $text ) ) {
2897 $found = true;
2898 $isHTML = true;
2899 $this->disableCache();
2900 }
2901 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2902 $found = false; //access denied
2903 wfDebug( __METHOD__.": template inclusion denied for " . $title->getPrefixedDBkey() );
2904 } else {
2905 list( $text, $title ) = $this->getTemplateDom( $title );
2906 if ( $text !== false ) {
2907 $found = true;
2908 $isChildObj = true;
2909 }
2910 }
2911
2912 # If the title is valid but undisplayable, make a link to it
2913 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
2914 $text = "[[:$titleText]]";
2915 $found = true;
2916 }
2917 } elseif ( $title->isTrans() ) {
2918 // Interwiki transclusion
2919 if ( $this->ot['html'] && !$forceRawInterwiki ) {
2920 $text = $this->interwikiTransclude( $title, 'render' );
2921 $isHTML = true;
2922 } else {
2923 $text = $this->interwikiTransclude( $title, 'raw' );
2924 // Preprocess it like a template
2925 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
2926 $isChildObj = true;
2927 }
2928 $found = true;
2929 }
2930 wfProfileOut( __METHOD__ . '-loadtpl' );
2931 }
2932
2933 # If we haven't found text to substitute by now, we're done
2934 # Recover the source wikitext and return it
2935 if ( !$found ) {
2936 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2937 wfProfileOut( __METHOD__ );
2938 return array( 'object' => $text );
2939 }
2940
2941 # Expand DOM-style return values in a child frame
2942 if ( $isChildObj ) {
2943 # Clean up argument array
2944 $newFrame = $frame->newChild( $args, $title );
2945
2946 if ( $nowiki ) {
2947 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
2948 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2949 # Expansion is eligible for the empty-frame cache
2950 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
2951 $text = $this->mTplExpandCache[$titleText];
2952 } else {
2953 $text = $newFrame->expand( $text );
2954 $this->mTplExpandCache[$titleText] = $text;
2955 }
2956 } else {
2957 # Uncached expansion
2958 $text = $newFrame->expand( $text );
2959 }
2960 }
2961 if ( $isLocalObj && $nowiki ) {
2962 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
2963 $isLocalObj = false;
2964 }
2965
2966 # Replace raw HTML by a placeholder
2967 # Add a blank line preceding, to prevent it from mucking up
2968 # immediately preceding headings
2969 if ( $isHTML ) {
2970 $text = "\n\n" . $this->insertStripItem( $text );
2971 }
2972 # Escape nowiki-style return values
2973 elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
2974 $text = wfEscapeWikiText( $text );
2975 }
2976 # Bug 529: if the template begins with a table or block-level
2977 # element, it should be treated as beginning a new line.
2978 # This behaviour is somewhat controversial.
2979 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
2980 $text = "\n" . $text;
2981 }
2982
2983 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
2984 # Error, oversize inclusion
2985 $text = "[[$originalTitle]]" .
2986 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
2987 $this->limitationWarn( 'post-expand-template-inclusion' );
2988 }
2989
2990 if ( $isLocalObj ) {
2991 $ret = array( 'object' => $text );
2992 } else {
2993 $ret = array( 'text' => $text );
2994 }
2995
2996 wfProfileOut( __METHOD__ );
2997 return $ret;
2998 }
2999
3000 /**
3001 * Get the semi-parsed DOM representation of a template with a given title,
3002 * and its redirect destination title. Cached.
3003 */
3004 function getTemplateDom( $title ) {
3005 $cacheTitle = $title;
3006 $titleText = $title->getPrefixedDBkey();
3007
3008 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3009 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3010 $title = Title::makeTitle( $ns, $dbk );
3011 $titleText = $title->getPrefixedDBkey();
3012 }
3013 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3014 return array( $this->mTplDomCache[$titleText], $title );
3015 }
3016
3017 // Cache miss, go to the database
3018 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3019
3020 if ( $text === false ) {
3021 $this->mTplDomCache[$titleText] = false;
3022 return array( false, $title );
3023 }
3024
3025 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3026 $this->mTplDomCache[ $titleText ] = $dom;
3027
3028 if (! $title->equals($cacheTitle)) {
3029 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3030 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3031 }
3032
3033 return array( $dom, $title );
3034 }
3035
3036 /**
3037 * Fetch the unparsed text of a template and register a reference to it.
3038 */
3039 function fetchTemplateAndTitle( $title ) {
3040 $templateCb = $this->mOptions->getTemplateCallback();
3041 $stuff = call_user_func( $templateCb, $title, $this );
3042 $text = $stuff['text'];
3043 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3044 if ( isset( $stuff['deps'] ) ) {
3045 foreach ( $stuff['deps'] as $dep ) {
3046 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3047 }
3048 }
3049 return array($text,$finalTitle);
3050 }
3051
3052 function fetchTemplate( $title ) {
3053 $rv = $this->fetchTemplateAndTitle($title);
3054 return $rv[0];
3055 }
3056
3057 /**
3058 * Static function to get a template
3059 * Can be overridden via ParserOptions::setTemplateCallback().
3060 */
3061 static function statelessFetchTemplate( $title, $parser=false ) {
3062 $text = $skip = false;
3063 $finalTitle = $title;
3064 $deps = array();
3065
3066 // Loop to fetch the article, with up to 1 redirect
3067 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3068 # Give extensions a chance to select the revision instead
3069 $id = false; // Assume current
3070 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3071
3072 if( $skip ) {
3073 $text = false;
3074 $deps[] = array(
3075 'title' => $title,
3076 'page_id' => $title->getArticleID(),
3077 'rev_id' => null );
3078 break;
3079 }
3080 $rev = $id ? Revision::newFromId( $id ) : Revision::newFromTitle( $title );
3081 $rev_id = $rev ? $rev->getId() : 0;
3082 // If there is no current revision, there is no page
3083 if( $id === false && !$rev ) {
3084 $linkCache = LinkCache::singleton();
3085 $linkCache->addBadLinkObj( $title );
3086 }
3087
3088 $deps[] = array(
3089 'title' => $title,
3090 'page_id' => $title->getArticleID(),
3091 'rev_id' => $rev_id );
3092
3093 if( $rev ) {
3094 $text = $rev->getText();
3095 } elseif( $title->getNamespace() == NS_MEDIAWIKI ) {
3096 global $wgLang;
3097 $message = $wgLang->lcfirst( $title->getText() );
3098 $text = wfMsgForContentNoTrans( $message );
3099 if( wfEmptyMsg( $message, $text ) ) {
3100 $text = false;
3101 break;
3102 }
3103 } else {
3104 break;
3105 }
3106 if ( $text === false ) {
3107 break;
3108 }
3109 // Redirect?
3110 $finalTitle = $title;
3111 $title = Title::newFromRedirect( $text );
3112 }
3113 return array(
3114 'text' => $text,
3115 'finalTitle' => $finalTitle,
3116 'deps' => $deps );
3117 }
3118
3119 /**
3120 * Transclude an interwiki link.
3121 */
3122 function interwikiTransclude( $title, $action ) {
3123 global $wgEnableScaryTranscluding;
3124
3125 if (!$wgEnableScaryTranscluding)
3126 return wfMsg('scarytranscludedisabled');
3127
3128 $url = $title->getFullUrl( "action=$action" );
3129
3130 if (strlen($url) > 255)
3131 return wfMsg('scarytranscludetoolong');
3132 return $this->fetchScaryTemplateMaybeFromCache($url);
3133 }
3134
3135 function fetchScaryTemplateMaybeFromCache($url) {
3136 global $wgTranscludeCacheExpiry;
3137 $dbr = wfGetDB(DB_SLAVE);
3138 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3139 array('tc_url' => $url));
3140 if ($obj) {
3141 $time = $obj->tc_time;
3142 $text = $obj->tc_contents;
3143 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
3144 return $text;
3145 }
3146 }
3147
3148 $text = Http::get($url);
3149 if (!$text)
3150 return wfMsg('scarytranscludefailed', $url);
3151
3152 $dbw = wfGetDB(DB_MASTER);
3153 $dbw->replace('transcache', array('tc_url'), array(
3154 'tc_url' => $url,
3155 'tc_time' => time(),
3156 'tc_contents' => $text));
3157 return $text;
3158 }
3159
3160
3161 /**
3162 * Triple brace replacement -- used for template arguments
3163 * @private
3164 */
3165 function argSubstitution( $piece, $frame ) {
3166 wfProfileIn( __METHOD__ );
3167
3168 $error = false;
3169 $parts = $piece['parts'];
3170 $nameWithSpaces = $frame->expand( $piece['title'] );
3171 $argName = trim( $nameWithSpaces );
3172 $object = false;
3173 $text = $frame->getArgument( $argName );
3174 if ( $text === false && $parts->getLength() > 0
3175 && (
3176 $this->ot['html']
3177 || $this->ot['pre']
3178 || ( $this->ot['wiki'] && $frame->isTemplate() )
3179 )
3180 ) {
3181 # No match in frame, use the supplied default
3182 $object = $parts->item( 0 )->getChildren();
3183 }
3184 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3185 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3186 $this->limitationWarn( 'post-expand-template-argument' );
3187 }
3188
3189 if ( $text === false && $object === false ) {
3190 # No match anywhere
3191 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3192 }
3193 if ( $error !== false ) {
3194 $text .= $error;
3195 }
3196 if ( $object !== false ) {
3197 $ret = array( 'object' => $object );
3198 } else {
3199 $ret = array( 'text' => $text );
3200 }
3201
3202 wfProfileOut( __METHOD__ );
3203 return $ret;
3204 }
3205
3206 /**
3207 * Return the text to be used for a given extension tag.
3208 * This is the ghost of strip().
3209 *
3210 * @param array $params Associative array of parameters:
3211 * name PPNode for the tag name
3212 * attr PPNode for unparsed text where tag attributes are thought to be
3213 * attributes Optional associative array of parsed attributes
3214 * inner Contents of extension element
3215 * noClose Original text did not have a close tag
3216 * @param PPFrame $frame
3217 */
3218 function extensionSubstitution( $params, $frame ) {
3219 global $wgRawHtml, $wgContLang;
3220
3221 $name = $frame->expand( $params['name'] );
3222 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3223 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3224
3225 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++) . self::MARKER_SUFFIX;
3226
3227 if ( $this->ot['html'] ) {
3228 $name = strtolower( $name );
3229
3230 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3231 if ( isset( $params['attributes'] ) ) {
3232 $attributes = $attributes + $params['attributes'];
3233 }
3234 switch ( $name ) {
3235 case 'html':
3236 if( $wgRawHtml ) {
3237 $output = $content;
3238 break;
3239 } else {
3240 throw new MWException( '<html> extension tag encountered unexpectedly' );
3241 }
3242 case 'nowiki':
3243 $output = Xml::escapeTagsOnly( $content );
3244 break;
3245 case 'math':
3246 $output = $wgContLang->armourMath(
3247 MathRenderer::renderMath( $content, $attributes ) );
3248 break;
3249 case 'gallery':
3250 $output = $this->renderImageGallery( $content, $attributes );
3251 break;
3252 default:
3253 if( isset( $this->mTagHooks[$name] ) ) {
3254 # Workaround for PHP bug 35229 and similar
3255 if ( !is_callable( $this->mTagHooks[$name] ) ) {
3256 throw new MWException( "Tag hook for $name is not callable\n" );
3257 }
3258 $output = call_user_func_array( $this->mTagHooks[$name],
3259 array( $content, $attributes, $this ) );
3260 } else {
3261 $output = '<span class="error">Invalid tag extension name: ' .
3262 htmlspecialchars( $name ) . '</span>';
3263 }
3264 }
3265 } else {
3266 if ( is_null( $attrText ) ) {
3267 $attrText = '';
3268 }
3269 if ( isset( $params['attributes'] ) ) {
3270 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3271 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3272 htmlspecialchars( $attrValue ) . '"';
3273 }
3274 }
3275 if ( $content === null ) {
3276 $output = "<$name$attrText/>";
3277 } else {
3278 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
3279 $output = "<$name$attrText>$content$close";
3280 }
3281 }
3282
3283 if ( $name === 'html' || $name === 'nowiki' ) {
3284 $this->mStripState->nowiki->setPair( $marker, $output );
3285 } else {
3286 $this->mStripState->general->setPair( $marker, $output );
3287 }
3288 return $marker;
3289 }
3290
3291 /**
3292 * Increment an include size counter
3293 *
3294 * @param string $type The type of expansion
3295 * @param integer $size The size of the text
3296 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3297 */
3298 function incrementIncludeSize( $type, $size ) {
3299 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize( $type ) ) {
3300 return false;
3301 } else {
3302 $this->mIncludeSizes[$type] += $size;
3303 return true;
3304 }
3305 }
3306
3307 /**
3308 * Increment the expensive function count
3309 *
3310 * @return boolean False if the limit has been exceeded
3311 */
3312 function incrementExpensiveFunctionCount() {
3313 global $wgExpensiveParserFunctionLimit;
3314 $this->mExpensiveFunctionCount++;
3315 if($this->mExpensiveFunctionCount <= $wgExpensiveParserFunctionLimit) {
3316 return true;
3317 }
3318 return false;
3319 }
3320
3321 /**
3322 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3323 * Fills $this->mDoubleUnderscores, returns the modified text
3324 */
3325 function doDoubleUnderscore( $text ) {
3326 // The position of __TOC__ needs to be recorded
3327 $mw = MagicWord::get( 'toc' );
3328 if( $mw->match( $text ) ) {
3329 $this->mShowToc = true;
3330 $this->mForceTocPosition = true;
3331
3332 // Set a placeholder. At the end we'll fill it in with the TOC.
3333 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3334
3335 // Only keep the first one.
3336 $text = $mw->replace( '', $text );
3337 }
3338
3339 // Now match and remove the rest of them
3340 $mwa = MagicWord::getDoubleUnderscoreArray();
3341 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
3342
3343 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
3344 $this->mOutput->mNoGallery = true;
3345 }
3346 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
3347 $this->mShowToc = false;
3348 }
3349 if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) {
3350 $this->mOutput->setProperty( 'hiddencat', 'y' );
3351
3352 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, wfMsgForContent( 'hidden-category-category' ) );
3353 if ( $containerCategory ) {
3354 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3355 } else {
3356 wfDebug( __METHOD__.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3357 }
3358 }
3359 # (bug 8068) Allow control over whether robots index a page.
3360 #
3361 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3362 # is not desirable, the last one on the page should win.
3363 if( isset( $this->mDoubleUnderscores['noindex'] ) ) {
3364 $this->mOutput->setIndexPolicy( 'noindex' );
3365 } elseif( isset( $this->mDoubleUnderscores['index'] ) ) {
3366 $this->mOutput->setIndexPolicy( 'index' );
3367 }
3368
3369 return $text;
3370 }
3371
3372 /**
3373 * This function accomplishes several tasks:
3374 * 1) Auto-number headings if that option is enabled
3375 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3376 * 3) Add a Table of contents on the top for users who have enabled the option
3377 * 4) Auto-anchor headings
3378 *
3379 * It loops through all headlines, collects the necessary data, then splits up the
3380 * string and re-inserts the newly formatted headlines.
3381 *
3382 * @param string $text
3383 * @param boolean $isMain
3384 * @private
3385 */
3386 function formatHeadings( $text, $isMain=true ) {
3387 global $wgMaxTocLevel, $wgContLang;
3388
3389 $doNumberHeadings = $this->mOptions->getNumberHeadings();
3390 if( !$this->mTitle->quickUserCan( 'edit' ) ) {
3391 $showEditLink = 0;
3392 } else {
3393 $showEditLink = $this->mOptions->getEditSection();
3394 }
3395
3396 # Inhibit editsection links if requested in the page
3397 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
3398 $showEditLink = 0;
3399 }
3400
3401 # Get all headlines for numbering them and adding funky stuff like [edit]
3402 # links - this is for later, but we need the number of headlines right now
3403 $matches = array();
3404 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3405
3406 # if there are fewer than 4 headlines in the article, do not show TOC
3407 # unless it's been explicitly enabled.
3408 $enoughToc = $this->mShowToc &&
3409 (($numMatches >= 4) || $this->mForceTocPosition);
3410
3411 # Allow user to stipulate that a page should have a "new section"
3412 # link added via __NEWSECTIONLINK__
3413 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
3414 $this->mOutput->setNewSection( true );
3415 }
3416
3417 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3418 # override above conditions and always show TOC above first header
3419 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
3420 $this->mShowToc = true;
3421 $enoughToc = true;
3422 }
3423
3424 # We need this to perform operations on the HTML
3425 $sk = $this->mOptions->getSkin();
3426
3427 # headline counter
3428 $headlineCount = 0;
3429 $numVisible = 0;
3430
3431 # Ugh .. the TOC should have neat indentation levels which can be
3432 # passed to the skin functions. These are determined here
3433 $toc = '';
3434 $full = '';
3435 $head = array();
3436 $sublevelCount = array();
3437 $levelCount = array();
3438 $toclevel = 0;
3439 $level = 0;
3440 $prevlevel = 0;
3441 $toclevel = 0;
3442 $prevtoclevel = 0;
3443 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
3444 $baseTitleText = $this->mTitle->getPrefixedDBkey();
3445 $tocraw = array();
3446
3447 foreach( $matches[3] as $headline ) {
3448 $isTemplate = false;
3449 $titleText = false;
3450 $sectionIndex = false;
3451 $numbering = '';
3452 $markerMatches = array();
3453 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3454 $serial = $markerMatches[1];
3455 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
3456 $isTemplate = ($titleText != $baseTitleText);
3457 $headline = preg_replace("/^$markerRegex/", "", $headline);
3458 }
3459
3460 if( $toclevel ) {
3461 $prevlevel = $level;
3462 $prevtoclevel = $toclevel;
3463 }
3464 $level = $matches[1][$headlineCount];
3465
3466 if( $doNumberHeadings || $enoughToc ) {
3467
3468 if ( $level > $prevlevel ) {
3469 # Increase TOC level
3470 $toclevel++;
3471 $sublevelCount[$toclevel] = 0;
3472 if( $toclevel<$wgMaxTocLevel ) {
3473 $prevtoclevel = $toclevel;
3474 $toc .= $sk->tocIndent();
3475 $numVisible++;
3476 }
3477 }
3478 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3479 # Decrease TOC level, find level to jump to
3480
3481 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3482 # Can only go down to level 1
3483 $toclevel = 1;
3484 } else {
3485 for ($i = $toclevel; $i > 0; $i--) {
3486 if ( $levelCount[$i] == $level ) {
3487 # Found last matching level
3488 $toclevel = $i;
3489 break;
3490 }
3491 elseif ( $levelCount[$i] < $level ) {
3492 # Found first matching level below current level
3493 $toclevel = $i + 1;
3494 break;
3495 }
3496 }
3497 }
3498 if( $toclevel<$wgMaxTocLevel ) {
3499 if($prevtoclevel < $wgMaxTocLevel) {
3500 # Unindent only if the previous toc level was shown :p
3501 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3502 $prevtoclevel = $toclevel;
3503 } else {
3504 $toc .= $sk->tocLineEnd();
3505 }
3506 }
3507 }
3508 else {
3509 # No change in level, end TOC line
3510 if( $toclevel<$wgMaxTocLevel ) {
3511 $toc .= $sk->tocLineEnd();
3512 }
3513 }
3514
3515 $levelCount[$toclevel] = $level;
3516
3517 # count number of headlines for each level
3518 @$sublevelCount[$toclevel]++;
3519 $dot = 0;
3520 for( $i = 1; $i <= $toclevel; $i++ ) {
3521 if( !empty( $sublevelCount[$i] ) ) {
3522 if( $dot ) {
3523 $numbering .= '.';
3524 }
3525 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3526 $dot = 1;
3527 }
3528 }
3529 }
3530
3531 # The safe header is a version of the header text safe to use for links
3532 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3533 $safeHeadline = $this->mStripState->unstripBoth( $headline );
3534
3535 # Remove link placeholders by the link text.
3536 # <!--LINK number-->
3537 # turns into
3538 # link text with suffix
3539 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3540
3541 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3542 $tocline = preg_replace(
3543 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3544 array( '', '<$1>'),
3545 $safeHeadline
3546 );
3547 $tocline = trim( $tocline );
3548
3549 # For the anchor, strip out HTML-y stuff period
3550 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3551 $safeHeadline = trim( $safeHeadline );
3552
3553 # Save headline for section edit hint before it's escaped
3554 $headlineHint = $safeHeadline;
3555 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
3556 # HTML names must be case-insensitively unique (bug 10721)
3557 $arrayKey = strtolower( $safeHeadline );
3558
3559 # count how many in assoc. array so we can track dupes in anchors
3560 isset( $refers[$arrayKey] ) ? $refers[$arrayKey]++ : $refers[$arrayKey] = 1;
3561 $refcount[$headlineCount] = $refers[$arrayKey];
3562
3563 # Don't number the heading if it is the only one (looks silly)
3564 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3565 # the two are different if the line contains a link
3566 $headline=$numbering . ' ' . $headline;
3567 }
3568
3569 # Create the anchor for linking from the TOC to the section
3570 $anchor = $safeHeadline;
3571 if($refcount[$headlineCount] > 1 ) {
3572 $anchor .= '_' . $refcount[$headlineCount];
3573 }
3574 if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3575 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3576 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3577 }
3578 # give headline the correct <h#> tag
3579 if( $showEditLink && $sectionIndex !== false ) {
3580 if( $isTemplate ) {
3581 # Put a T flag in the section identifier, to indicate to extractSections()
3582 # that sections inside <includeonly> should be counted.
3583 $editlink = $sk->doEditSectionLink(Title::newFromText( $titleText ), "T-$sectionIndex");
3584 } else {
3585 $editlink = $sk->doEditSectionLink($this->mTitle, $sectionIndex, $headlineHint);
3586 }
3587 } else {
3588 $editlink = '';
3589 }
3590 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3591
3592 $headlineCount++;
3593 }
3594
3595 $this->mOutput->setSections( $tocraw );
3596
3597 # Never ever show TOC if no headers
3598 if( $numVisible < 1 ) {
3599 $enoughToc = false;
3600 }
3601
3602 if( $enoughToc ) {
3603 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3604 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3605 }
3606 $toc = $sk->tocList( $toc );
3607 }
3608
3609 # split up and insert constructed headlines
3610
3611 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3612 $i = 0;
3613
3614 foreach( $blocks as $block ) {
3615 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3616 # This is the [edit] link that appears for the top block of text when
3617 # section editing is enabled
3618
3619 # Disabled because it broke block formatting
3620 # For example, a bullet point in the top line
3621 # $full .= $sk->editSectionLink(0);
3622 }
3623 $full .= $block;
3624 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
3625 # Top anchor now in skin
3626 $full = $full.$toc;
3627 }
3628
3629 if( !empty( $head[$i] ) ) {
3630 $full .= $head[$i];
3631 }
3632 $i++;
3633 }
3634 if( $this->mForceTocPosition ) {
3635 return str_replace( '<!--MWTOC-->', $toc, $full );
3636 } else {
3637 return $full;
3638 }
3639 }
3640
3641 /**
3642 * Transform wiki markup when saving a page by doing \r\n -> \n
3643 * conversion, substitting signatures, {{subst:}} templates, etc.
3644 *
3645 * @param string $text the text to transform
3646 * @param Title &$title the Title object for the current article
3647 * @param User &$user the User object describing the current user
3648 * @param ParserOptions $options parsing options
3649 * @param bool $clearState whether to clear the parser state first
3650 * @return string the altered wiki markup
3651 * @public
3652 */
3653 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3654 $this->mOptions = $options;
3655 $this->setTitle( $title );
3656 $this->setOutputType( self::OT_WIKI );
3657
3658 if ( $clearState ) {
3659 $this->clearState();
3660 }
3661
3662 $pairs = array(
3663 "\r\n" => "\n",
3664 );
3665 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3666 $text = $this->pstPass2( $text, $user );
3667 $text = $this->mStripState->unstripBoth( $text );
3668 return $text;
3669 }
3670
3671 /**
3672 * Pre-save transform helper function
3673 * @private
3674 */
3675 function pstPass2( $text, $user ) {
3676 global $wgContLang, $wgLocaltimezone;
3677
3678 /* Note: This is the timestamp saved as hardcoded wikitext to
3679 * the database, we use $wgContLang here in order to give
3680 * everyone the same signature and use the default one rather
3681 * than the one selected in each user's preferences.
3682 *
3683 * (see also bug 12815)
3684 */
3685 $ts = $this->mOptions->getTimestamp();
3686 $tz = wfMsgForContent( 'timezone-utc' );
3687 if ( isset( $wgLocaltimezone ) ) {
3688 $unixts = wfTimestamp( TS_UNIX, $ts );
3689 $oldtz = getenv( 'TZ' );
3690 putenv( 'TZ='.$wgLocaltimezone );
3691 $ts = date( 'YmdHis', $unixts );
3692 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3693 putenv( 'TZ='.$oldtz );
3694 }
3695
3696 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3697
3698 # Variable replacement
3699 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3700 $text = $this->replaceVariables( $text );
3701
3702 # Signatures
3703 $sigText = $this->getUserSig( $user );
3704 $text = strtr( $text, array(
3705 '~~~~~' => $d,
3706 '~~~~' => "$sigText $d",
3707 '~~~' => $sigText
3708 ) );
3709
3710 # Context links: [[|name]] and [[name (context)|]]
3711 #
3712 global $wgLegalTitleChars;
3713 $tc = "[$wgLegalTitleChars]";
3714 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3715
3716 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3717 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
3718 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3719 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3720
3721 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3722 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3723 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
3724 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3725
3726 $t = $this->mTitle->getText();
3727 $m = array();
3728 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3729 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3730 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3731 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3732 } else {
3733 # if there's no context, don't bother duplicating the title
3734 $text = preg_replace( $p2, '[[\\1]]', $text );
3735 }
3736
3737 # Trim trailing whitespace
3738 $text = rtrim( $text );
3739
3740 return $text;
3741 }
3742
3743 /**
3744 * Fetch the user's signature text, if any, and normalize to
3745 * validated, ready-to-insert wikitext.
3746 *
3747 * @param User $user
3748 * @return string
3749 * @private
3750 */
3751 function getUserSig( &$user ) {
3752 global $wgMaxSigChars;
3753
3754 $username = $user->getName();
3755 $nickname = $user->getOption( 'nickname' );
3756 $nickname = $nickname === '' ? $username : $nickname;
3757
3758 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3759 $nickname = $username;
3760 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
3761 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3762 # Sig. might contain markup; validate this
3763 if( $this->validateSig( $nickname ) !== false ) {
3764 # Validated; clean up (if needed) and return it
3765 return $this->cleanSig( $nickname, true );
3766 } else {
3767 # Failed to validate; fall back to the default
3768 $nickname = $username;
3769 wfDebug( __METHOD__.": $username has bad XML tags in signature.\n" );
3770 }
3771 }
3772
3773 // Make sure nickname doesnt get a sig in a sig
3774 $nickname = $this->cleanSigInSig( $nickname );
3775
3776 # If we're still here, make it a link to the user page
3777 $userText = wfEscapeWikiText( $username );
3778 $nickText = wfEscapeWikiText( $nickname );
3779 if ( $user->isAnon() ) {
3780 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3781 } else {
3782 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3783 }
3784 }
3785
3786 /**
3787 * Check that the user's signature contains no bad XML
3788 *
3789 * @param string $text
3790 * @return mixed An expanded string, or false if invalid.
3791 */
3792 function validateSig( $text ) {
3793 return( wfIsWellFormedXmlFragment( $text ) ? $text : false );
3794 }
3795
3796 /**
3797 * Clean up signature text
3798 *
3799 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3800 * 2) Substitute all transclusions
3801 *
3802 * @param string $text
3803 * @param $parsing Whether we're cleaning (preferences save) or parsing
3804 * @return string Signature text
3805 */
3806 function cleanSig( $text, $parsing = false ) {
3807 if ( !$parsing ) {
3808 global $wgTitle;
3809 $this->clearState();
3810 $this->setTitle( $wgTitle );
3811 $this->mOptions = new ParserOptions;
3812 $this->setOutputType = self::OT_PREPROCESS;
3813 }
3814
3815 # Option to disable this feature
3816 if ( !$this->mOptions->getCleanSignatures() ) {
3817 return $text;
3818 }
3819
3820 # FIXME: regex doesn't respect extension tags or nowiki
3821 # => Move this logic to braceSubstitution()
3822 $substWord = MagicWord::get( 'subst' );
3823 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3824 $substText = '{{' . $substWord->getSynonym( 0 );
3825
3826 $text = preg_replace( $substRegex, $substText, $text );
3827 $text = $this->cleanSigInSig( $text );
3828 $dom = $this->preprocessToDom( $text );
3829 $frame = $this->getPreprocessor()->newFrame();
3830 $text = $frame->expand( $dom );
3831
3832 if ( !$parsing ) {
3833 $text = $this->mStripState->unstripBoth( $text );
3834 }
3835
3836 return $text;
3837 }
3838
3839 /**
3840 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3841 * @param string $text
3842 * @return string Signature text with /~{3,5}/ removed
3843 */
3844 function cleanSigInSig( $text ) {
3845 $text = preg_replace( '/~{3,5}/', '', $text );
3846 return $text;
3847 }
3848
3849 /**
3850 * Set up some variables which are usually set up in parse()
3851 * so that an external function can call some class members with confidence
3852 * @public
3853 */
3854 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3855 $this->setTitle( $title );
3856 $this->mOptions = $options;
3857 $this->setOutputType( $outputType );
3858 if ( $clearState ) {
3859 $this->clearState();
3860 }
3861 }
3862
3863 /**
3864 * Wrapper for preprocess()
3865 *
3866 * @param string $text the text to preprocess
3867 * @param ParserOptions $options options
3868 * @return string
3869 * @public
3870 */
3871 function transformMsg( $text, $options ) {
3872 global $wgTitle;
3873 static $executing = false;
3874
3875 # Guard against infinite recursion
3876 if ( $executing ) {
3877 return $text;
3878 }
3879 $executing = true;
3880
3881 wfProfileIn(__METHOD__);
3882 $text = $this->preprocess( $text, $wgTitle, $options );
3883
3884 $executing = false;
3885 wfProfileOut(__METHOD__);
3886 return $text;
3887 }
3888
3889 /**
3890 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3891 * The callback should have the following form:
3892 * function myParserHook( $text, $params, &$parser ) { ... }
3893 *
3894 * Transform and return $text. Use $parser for any required context, e.g. use
3895 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3896 *
3897 * @public
3898 *
3899 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3900 * @param mixed $callback The callback function (and object) to use for the tag
3901 *
3902 * @return The old value of the mTagHooks array associated with the hook
3903 */
3904 function setHook( $tag, $callback ) {
3905 $tag = strtolower( $tag );
3906 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
3907 $this->mTagHooks[$tag] = $callback;
3908 if( !in_array( $tag, $this->mStripList ) ) {
3909 $this->mStripList[] = $tag;
3910 }
3911
3912 return $oldVal;
3913 }
3914
3915 function setTransparentTagHook( $tag, $callback ) {
3916 $tag = strtolower( $tag );
3917 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
3918 $this->mTransparentTagHooks[$tag] = $callback;
3919
3920 return $oldVal;
3921 }
3922
3923 /**
3924 * Remove all tag hooks
3925 */
3926 function clearTagHooks() {
3927 $this->mTagHooks = array();
3928 $this->mStripList = $this->mDefaultStripList;
3929 }
3930
3931 /**
3932 * Create a function, e.g. {{sum:1|2|3}}
3933 * The callback function should have the form:
3934 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3935 *
3936 * Or with SFH_OBJECT_ARGS:
3937 * function myParserFunction( $parser, $frame, $args ) { ... }
3938 *
3939 * The callback may either return the text result of the function, or an array with the text
3940 * in element 0, and a number of flags in the other elements. The names of the flags are
3941 * specified in the keys. Valid flags are:
3942 * found The text returned is valid, stop processing the template. This
3943 * is on by default.
3944 * nowiki Wiki markup in the return value should be escaped
3945 * isHTML The returned text is HTML, armour it against wikitext transformation
3946 *
3947 * @public
3948 *
3949 * @param string $id The magic word ID
3950 * @param mixed $callback The callback function (and object) to use
3951 * @param integer $flags a combination of the following flags:
3952 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3953 *
3954 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
3955 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
3956 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
3957 * the arguments, and to control the way they are expanded.
3958 *
3959 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
3960 * arguments, for instance:
3961 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
3962 *
3963 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
3964 * future versions. Please call $frame->expand() on it anyway so that your code keeps
3965 * working if/when this is changed.
3966 *
3967 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
3968 * expansion.
3969 *
3970 * Please read the documentation in includes/parser/Preprocessor.php for more information
3971 * about the methods available in PPFrame and PPNode.
3972 *
3973 * @return The old callback function for this name, if any
3974 */
3975 function setFunctionHook( $id, $callback, $flags = 0 ) {
3976 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
3977 $this->mFunctionHooks[$id] = array( $callback, $flags );
3978
3979 # Add to function cache
3980 $mw = MagicWord::get( $id );
3981 if( !$mw )
3982 throw new MWException( __METHOD__.'() expecting a magic word identifier.' );
3983
3984 $synonyms = $mw->getSynonyms();
3985 $sensitive = intval( $mw->isCaseSensitive() );
3986
3987 foreach ( $synonyms as $syn ) {
3988 # Case
3989 if ( !$sensitive ) {
3990 $syn = strtolower( $syn );
3991 }
3992 # Add leading hash
3993 if ( !( $flags & SFH_NO_HASH ) ) {
3994 $syn = '#' . $syn;
3995 }
3996 # Remove trailing colon
3997 if ( substr( $syn, -1, 1 ) === ':' ) {
3998 $syn = substr( $syn, 0, -1 );
3999 }
4000 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4001 }
4002 return $oldVal;
4003 }
4004
4005 /**
4006 * Get all registered function hook identifiers
4007 *
4008 * @return array
4009 */
4010 function getFunctionHooks() {
4011 return array_keys( $this->mFunctionHooks );
4012 }
4013
4014 /**
4015 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4016 * Placeholders created in Skin::makeLinkObj()
4017 * Returns an array of link CSS classes, indexed by PDBK.
4018 */
4019 function replaceLinkHolders( &$text, $options = 0 ) {
4020 return $this->mLinkHolders->replace( $text );
4021 }
4022
4023 /**
4024 * Replace <!--LINK--> link placeholders with plain text of links
4025 * (not HTML-formatted).
4026 * @param string $text
4027 * @return string
4028 */
4029 function replaceLinkHoldersText( $text ) {
4030 return $this->mLinkHolders->replaceText( $text );
4031 }
4032
4033 /**
4034 * Tag hook handler for 'pre'.
4035 */
4036 function renderPreTag( $text, $attribs ) {
4037 // Backwards-compatibility hack
4038 $content = StringUtils::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4039
4040 $attribs = Sanitizer::validateTagAttributes( $attribs, 'pre' );
4041 return wfOpenElement( 'pre', $attribs ) .
4042 Xml::escapeTagsOnly( $content ) .
4043 '</pre>';
4044 }
4045
4046 /**
4047 * Renders an image gallery from a text with one line per image.
4048 * text labels may be given by using |-style alternative text. E.g.
4049 * Image:one.jpg|The number "1"
4050 * Image:tree.jpg|A tree
4051 * given as text will return the HTML of a gallery with two images,
4052 * labeled 'The number "1"' and
4053 * 'A tree'.
4054 */
4055 function renderImageGallery( $text, $params ) {
4056 $ig = new ImageGallery();
4057 $ig->setContextTitle( $this->mTitle );
4058 $ig->setShowBytes( false );
4059 $ig->setShowFilename( false );
4060 $ig->setParser( $this );
4061 $ig->setHideBadImages();
4062 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
4063 $ig->useSkin( $this->mOptions->getSkin() );
4064 $ig->mRevisionId = $this->mRevisionId;
4065
4066 if( isset( $params['caption'] ) ) {
4067 $caption = $params['caption'];
4068 $caption = htmlspecialchars( $caption );
4069 $caption = $this->replaceInternalLinks( $caption );
4070 $ig->setCaptionHtml( $caption );
4071 }
4072 if( isset( $params['perrow'] ) ) {
4073 $ig->setPerRow( $params['perrow'] );
4074 }
4075 if( isset( $params['widths'] ) ) {
4076 $ig->setWidths( $params['widths'] );
4077 }
4078 if( isset( $params['heights'] ) ) {
4079 $ig->setHeights( $params['heights'] );
4080 }
4081
4082 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4083
4084 $lines = StringUtils::explode( "\n", $text );
4085 foreach ( $lines as $line ) {
4086 # match lines like these:
4087 # Image:someimage.jpg|This is some image
4088 $matches = array();
4089 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4090 # Skip empty lines
4091 if ( count( $matches ) == 0 ) {
4092 continue;
4093 }
4094
4095 if ( strpos( $matches[0], '%' ) !== false )
4096 $matches[1] = urldecode( $matches[1] );
4097 $tp = Title::newFromText( $matches[1]/*, NS_IMAGE*/ );
4098 $nt =& $tp;
4099 if( is_null( $nt ) ) {
4100 # Bogus title. Ignore these so we don't bomb out later.
4101 continue;
4102 }
4103 if ( isset( $matches[3] ) ) {
4104 $label = $matches[3];
4105 } else {
4106 $label = '';
4107 }
4108
4109 $html = $this->recursiveTagParse( trim( $label ) );
4110
4111 $ig->add( $nt, $html );
4112
4113 # Only add real images (bug #5586)
4114 if ( $nt->getNamespace() == NS_IMAGE ) {
4115 $this->mOutput->addImage( $nt->getDBkey() );
4116 }
4117 }
4118 return $ig->toHTML();
4119 }
4120
4121 function getImageParams( $handler ) {
4122 if ( $handler ) {
4123 $handlerClass = get_class( $handler );
4124 } else {
4125 $handlerClass = '';
4126 }
4127 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
4128 // Initialise static lists
4129 static $internalParamNames = array(
4130 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4131 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4132 'bottom', 'text-bottom' ),
4133 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4134 'upright', 'border' ),
4135 );
4136 static $internalParamMap;
4137 if ( !$internalParamMap ) {
4138 $internalParamMap = array();
4139 foreach ( $internalParamNames as $type => $names ) {
4140 foreach ( $names as $name ) {
4141 $magicName = str_replace( '-', '_', "img_$name" );
4142 $internalParamMap[$magicName] = array( $type, $name );
4143 }
4144 }
4145 }
4146
4147 // Add handler params
4148 $paramMap = $internalParamMap;
4149 if ( $handler ) {
4150 $handlerParamMap = $handler->getParamMap();
4151 foreach ( $handlerParamMap as $magic => $paramName ) {
4152 $paramMap[$magic] = array( 'handler', $paramName );
4153 }
4154 }
4155 $this->mImageParams[$handlerClass] = $paramMap;
4156 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4157 }
4158 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
4159 }
4160
4161 /**
4162 * Parse image options text and use it to make an image
4163 * @param Title $title
4164 * @param string $options
4165 * @param LinkHolderArray $holders
4166 */
4167 function makeImage( $title, $options, $holders = false ) {
4168 # Check if the options text is of the form "options|alt text"
4169 # Options are:
4170 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4171 # * left no resizing, just left align. label is used for alt= only
4172 # * right same, but right aligned
4173 # * none same, but not aligned
4174 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4175 # * center center the image
4176 # * framed Keep original image size, no magnify-button.
4177 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4178 # * upright reduce width for upright images, rounded to full __0 px
4179 # * border draw a 1px border around the image
4180 # vertical-align values (no % or length right now):
4181 # * baseline
4182 # * sub
4183 # * super
4184 # * top
4185 # * text-top
4186 # * middle
4187 # * bottom
4188 # * text-bottom
4189
4190 $parts = StringUtils::explode( "|", $options );
4191 $sk = $this->mOptions->getSkin();
4192
4193 # Give extensions a chance to select the file revision for us
4194 $skip = $time = $descQuery = false;
4195 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4196
4197 if ( $skip ) {
4198 return $sk->link( $title );
4199 }
4200
4201 # Get parameter map
4202 $file = wfFindFile( $title, $time );
4203 $handler = $file ? $file->getHandler() : false;
4204
4205 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4206
4207 # Process the input parameters
4208 $caption = '';
4209 $params = array( 'frame' => array(), 'handler' => array(),
4210 'horizAlign' => array(), 'vertAlign' => array() );
4211 foreach( $parts as $part ) {
4212 $part = trim( $part );
4213 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4214 $validated = false;
4215 if( isset( $paramMap[$magicName] ) ) {
4216 list( $type, $paramName ) = $paramMap[$magicName];
4217
4218 // Special case; width and height come in one variable together
4219 if( $type === 'handler' && $paramName === 'width' ) {
4220 $m = array();
4221 # (bug 13500) In both cases (width/height and width only),
4222 # permit trailing "px" for backward compatibility.
4223 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4224 $width = intval( $m[1] );
4225 $height = intval( $m[2] );
4226 if ( $handler->validateParam( 'width', $width ) ) {
4227 $params[$type]['width'] = $width;
4228 $validated = true;
4229 }
4230 if ( $handler->validateParam( 'height', $height ) ) {
4231 $params[$type]['height'] = $height;
4232 $validated = true;
4233 }
4234 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4235 $width = intval( $value );
4236 if ( $handler->validateParam( 'width', $width ) ) {
4237 $params[$type]['width'] = $width;
4238 $validated = true;
4239 }
4240 } // else no validation -- bug 13436
4241 } else {
4242 if ( $type === 'handler' ) {
4243 # Validate handler parameter
4244 $validated = $handler->validateParam( $paramName, $value );
4245 } else {
4246 # Validate internal parameters
4247 switch( $paramName ) {
4248 case "manualthumb":
4249 /// @fixme - possibly check validity here?
4250 /// downstream behavior seems odd with missing manual thumbs.
4251 $validated = true;
4252 break;
4253 default:
4254 // Most other things appear to be empty or numeric...
4255 $validated = ( $value === false || is_numeric( trim( $value ) ) );
4256 }
4257 }
4258
4259 if ( $validated ) {
4260 $params[$type][$paramName] = $value;
4261 }
4262 }
4263 }
4264 if ( !$validated ) {
4265 $caption = $part;
4266 }
4267 }
4268
4269 # Process alignment parameters
4270 if ( $params['horizAlign'] ) {
4271 $params['frame']['align'] = key( $params['horizAlign'] );
4272 }
4273 if ( $params['vertAlign'] ) {
4274 $params['frame']['valign'] = key( $params['vertAlign'] );
4275 }
4276
4277 # Strip bad stuff out of the alt text
4278 # We can't just use replaceLinkHoldersText() here, because if this function
4279 # is called from replaceInternalLinks2(), mLinkHolders won't be up to date.
4280 if ( $holders ) {
4281 $alt = $holders->replaceText( $caption );
4282 } else {
4283 $alt = $this->replaceLinkHoldersText( $caption );
4284 }
4285
4286 # make sure there are no placeholders in thumbnail attributes
4287 # that are later expanded to html- so expand them now and
4288 # remove the tags
4289 $alt = $this->mStripState->unstripBoth( $alt );
4290 $alt = Sanitizer::stripAllTags( $alt );
4291
4292 $params['frame']['alt'] = $alt;
4293 $params['frame']['caption'] = $caption;
4294
4295 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4296
4297 # Linker does the rest
4298 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4299
4300 # Give the handler a chance to modify the parser object
4301 if ( $handler ) {
4302 $handler->parserTransformHook( $this, $file );
4303 }
4304
4305 return $ret;
4306 }
4307
4308 /**
4309 * Set a flag in the output object indicating that the content is dynamic and
4310 * shouldn't be cached.
4311 */
4312 function disableCache() {
4313 wfDebug( "Parser output marked as uncacheable.\n" );
4314 $this->mOutput->mCacheTime = -1;
4315 }
4316
4317 /**#@+
4318 * Callback from the Sanitizer for expanding items found in HTML attribute
4319 * values, so they can be safely tested and escaped.
4320 * @param string $text
4321 * @param PPFrame $frame
4322 * @return string
4323 * @private
4324 */
4325 function attributeStripCallback( &$text, $frame = false ) {
4326 $text = $this->replaceVariables( $text, $frame );
4327 $text = $this->mStripState->unstripBoth( $text );
4328 return $text;
4329 }
4330
4331 /**#@-*/
4332
4333 /**#@+
4334 * Accessor/mutator
4335 */
4336 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
4337 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
4338 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
4339 /**#@-*/
4340
4341 /**#@+
4342 * Accessor
4343 */
4344 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks), array_keys( $this->mTagHooks ) ); }
4345 /**#@-*/
4346
4347
4348 /**
4349 * Break wikitext input into sections, and either pull or replace
4350 * some particular section's text.
4351 *
4352 * External callers should use the getSection and replaceSection methods.
4353 *
4354 * @param string $text Page wikitext
4355 * @param string $section A section identifier string of the form:
4356 * <flag1> - <flag2> - ... - <section number>
4357 *
4358 * Currently the only recognised flag is "T", which means the target section number
4359 * was derived during a template inclusion parse, in other words this is a template
4360 * section edit link. If no flags are given, it was an ordinary section edit link.
4361 * This flag is required to avoid a section numbering mismatch when a section is
4362 * enclosed by <includeonly> (bug 6563).
4363 *
4364 * The section number 0 pulls the text before the first heading; other numbers will
4365 * pull the given section along with its lower-level subsections. If the section is
4366 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4367 *
4368 * @param string $mode One of "get" or "replace"
4369 * @param string $newText Replacement text for section data.
4370 * @return string for "get", the extracted section text.
4371 * for "replace", the whole page with the section replaced.
4372 */
4373 private function extractSections( $text, $section, $mode, $newText='' ) {
4374 global $wgTitle;
4375 $this->clearState();
4376 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4377 $this->mOptions = new ParserOptions;
4378 $this->setOutputType( self::OT_WIKI );
4379 $outText = '';
4380 $frame = $this->getPreprocessor()->newFrame();
4381
4382 // Process section extraction flags
4383 $flags = 0;
4384 $sectionParts = explode( '-', $section );
4385 $sectionIndex = array_pop( $sectionParts );
4386 foreach ( $sectionParts as $part ) {
4387 if ( $part === 'T' ) {
4388 $flags |= self::PTD_FOR_INCLUSION;
4389 }
4390 }
4391 // Preprocess the text
4392 $root = $this->preprocessToDom( $text, $flags );
4393
4394 // <h> nodes indicate section breaks
4395 // They can only occur at the top level, so we can find them by iterating the root's children
4396 $node = $root->getFirstChild();
4397
4398 // Find the target section
4399 if ( $sectionIndex == 0 ) {
4400 // Section zero doesn't nest, level=big
4401 $targetLevel = 1000;
4402 } else {
4403 while ( $node ) {
4404 if ( $node->getName() === 'h' ) {
4405 $bits = $node->splitHeading();
4406 if ( $bits['i'] == $sectionIndex ) {
4407 $targetLevel = $bits['level'];
4408 break;
4409 }
4410 }
4411 if ( $mode === 'replace' ) {
4412 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4413 }
4414 $node = $node->getNextSibling();
4415 }
4416 }
4417
4418 if ( !$node ) {
4419 // Not found
4420 if ( $mode === 'get' ) {
4421 return $newText;
4422 } else {
4423 return $text;
4424 }
4425 }
4426
4427 // Find the end of the section, including nested sections
4428 do {
4429 if ( $node->getName() === 'h' ) {
4430 $bits = $node->splitHeading();
4431 $curLevel = $bits['level'];
4432 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4433 break;
4434 }
4435 }
4436 if ( $mode === 'get' ) {
4437 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4438 }
4439 $node = $node->getNextSibling();
4440 } while ( $node );
4441
4442 // Write out the remainder (in replace mode only)
4443 if ( $mode === 'replace' ) {
4444 // Output the replacement text
4445 // Add two newlines on -- trailing whitespace in $newText is conventionally
4446 // stripped by the editor, so we need both newlines to restore the paragraph gap
4447 $outText .= $newText . "\n\n";
4448 while ( $node ) {
4449 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4450 $node = $node->getNextSibling();
4451 }
4452 }
4453
4454 if ( is_string( $outText ) ) {
4455 // Re-insert stripped tags
4456 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
4457 }
4458
4459 return $outText;
4460 }
4461
4462 /**
4463 * This function returns the text of a section, specified by a number ($section).
4464 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4465 * the first section before any such heading (section 0).
4466 *
4467 * If a section contains subsections, these are also returned.
4468 *
4469 * @param string $text text to look in
4470 * @param string $section section identifier
4471 * @param string $deftext default to return if section is not found
4472 * @return string text of the requested section
4473 */
4474 public function getSection( $text, $section, $deftext='' ) {
4475 return $this->extractSections( $text, $section, "get", $deftext );
4476 }
4477
4478 public function replaceSection( $oldtext, $section, $text ) {
4479 return $this->extractSections( $oldtext, $section, "replace", $text );
4480 }
4481
4482 /**
4483 * Get the timestamp associated with the current revision, adjusted for
4484 * the default server-local timestamp
4485 */
4486 function getRevisionTimestamp() {
4487 if ( is_null( $this->mRevisionTimestamp ) ) {
4488 wfProfileIn( __METHOD__ );
4489 global $wgContLang;
4490 $dbr = wfGetDB( DB_SLAVE );
4491 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4492 array( 'rev_id' => $this->mRevisionId ), __METHOD__ );
4493
4494 // Normalize timestamp to internal MW format for timezone processing.
4495 // This has the added side-effect of replacing a null value with
4496 // the current time, which gives us more sensible behavior for
4497 // previews.
4498 $timestamp = wfTimestamp( TS_MW, $timestamp );
4499
4500 // The cryptic '' timezone parameter tells to use the site-default
4501 // timezone offset instead of the user settings.
4502 //
4503 // Since this value will be saved into the parser cache, served
4504 // to other users, and potentially even used inside links and such,
4505 // it needs to be consistent for all visitors.
4506 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
4507
4508 wfProfileOut( __METHOD__ );
4509 }
4510 return $this->mRevisionTimestamp;
4511 }
4512
4513 /**
4514 * Mutator for $mDefaultSort
4515 *
4516 * @param $sort New value
4517 */
4518 public function setDefaultSort( $sort ) {
4519 $this->mDefaultSort = $sort;
4520 }
4521
4522 /**
4523 * Accessor for $mDefaultSort
4524 * Will use the title/prefixed title if none is set
4525 *
4526 * @return string
4527 */
4528 public function getDefaultSort() {
4529 global $wgCategoryPrefixedDefaultSortkey;
4530 if( $this->mDefaultSort !== false ) {
4531 return $this->mDefaultSort;
4532 } elseif ($this->mTitle->getNamespace() == NS_CATEGORY ||
4533 !$wgCategoryPrefixedDefaultSortkey) {
4534 return $this->mTitle->getText();
4535 } else {
4536 return $this->mTitle->getPrefixedText();
4537 }
4538 }
4539
4540 /**
4541 * Try to guess the section anchor name based on a wikitext fragment
4542 * presumably extracted from a heading, for example "Header" from
4543 * "== Header ==".
4544 */
4545 public function guessSectionNameFromWikiText( $text ) {
4546 # Strip out wikitext links(they break the anchor)
4547 $text = $this->stripSectionName( $text );
4548 $headline = Sanitizer::decodeCharReferences( $text );
4549 # strip out HTML
4550 $headline = StringUtils::delimiterReplace( '<', '>', '', $headline );
4551 $headline = trim( $headline );
4552 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4553 $replacearray = array(
4554 '%3A' => ':',
4555 '%' => '.'
4556 );
4557 return str_replace(
4558 array_keys( $replacearray ),
4559 array_values( $replacearray ),
4560 $sectionanchor );
4561 }
4562
4563 /**
4564 * Strips a text string of wikitext for use in a section anchor
4565 *
4566 * Accepts a text string and then removes all wikitext from the
4567 * string and leaves only the resultant text (i.e. the result of
4568 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4569 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4570 * to create valid section anchors by mimicing the output of the
4571 * parser when headings are parsed.
4572 *
4573 * @param $text string Text string to be stripped of wikitext
4574 * for use in a Section anchor
4575 * @return Filtered text string
4576 */
4577 public function stripSectionName( $text ) {
4578 # Strip internal link markup
4579 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4580 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4581
4582 # Strip external link markup (FIXME: Not Tolerant to blank link text
4583 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4584 # on how many empty links there are on the page - need to figure that out.
4585 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4586
4587 # Parse wikitext quotes (italics & bold)
4588 $text = $this->doQuotes($text);
4589
4590 # Strip HTML tags
4591 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
4592 return $text;
4593 }
4594
4595 function srvus( $text ) {
4596 return $this->testSrvus( $text, $this->mOutputType );
4597 }
4598
4599 /**
4600 * strip/replaceVariables/unstrip for preprocessor regression testing
4601 */
4602 function testSrvus( $text, $title, $options, $outputType = self::OT_HTML ) {
4603 $this->clearState();
4604 if ( ! ( $title instanceof Title ) ) {
4605 $title = Title::newFromText( $title );
4606 }
4607 $this->mTitle = $title;
4608 $this->mOptions = $options;
4609 $this->setOutputType( $outputType );
4610 $text = $this->replaceVariables( $text );
4611 $text = $this->mStripState->unstripBoth( $text );
4612 $text = Sanitizer::removeHTMLtags( $text );
4613 return $text;
4614 }
4615
4616 function testPst( $text, $title, $options ) {
4617 global $wgUser;
4618 if ( ! ( $title instanceof Title ) ) {
4619 $title = Title::newFromText( $title );
4620 }
4621 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4622 }
4623
4624 function testPreprocess( $text, $title, $options ) {
4625 if ( ! ( $title instanceof Title ) ) {
4626 $title = Title::newFromText( $title );
4627 }
4628 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
4629 }
4630
4631 function markerSkipCallback( $s, $callback ) {
4632 $i = 0;
4633 $out = '';
4634 while ( $i < strlen( $s ) ) {
4635 $markerStart = strpos( $s, $this->mUniqPrefix, $i );
4636 if ( $markerStart === false ) {
4637 $out .= call_user_func( $callback, substr( $s, $i ) );
4638 break;
4639 } else {
4640 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4641 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
4642 if ( $markerEnd === false ) {
4643 $out .= substr( $s, $markerStart );
4644 break;
4645 } else {
4646 $markerEnd += strlen( self::MARKER_SUFFIX );
4647 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4648 $i = $markerEnd;
4649 }
4650 }
4651 }
4652 return $out;
4653 }
4654 }
4655
4656 /**
4657 * @todo document, briefly.
4658 * @ingroup Parser
4659 */
4660 class StripState {
4661 var $general, $nowiki;
4662
4663 function __construct() {
4664 $this->general = new ReplacementArray;
4665 $this->nowiki = new ReplacementArray;
4666 }
4667
4668 function unstripGeneral( $text ) {
4669 wfProfileIn( __METHOD__ );
4670 do {
4671 $oldText = $text;
4672 $text = $this->general->replace( $text );
4673 } while ( $text !== $oldText );
4674 wfProfileOut( __METHOD__ );
4675 return $text;
4676 }
4677
4678 function unstripNoWiki( $text ) {
4679 wfProfileIn( __METHOD__ );
4680 do {
4681 $oldText = $text;
4682 $text = $this->nowiki->replace( $text );
4683 } while ( $text !== $oldText );
4684 wfProfileOut( __METHOD__ );
4685 return $text;
4686 }
4687
4688 function unstripBoth( $text ) {
4689 wfProfileIn( __METHOD__ );
4690 do {
4691 $oldText = $text;
4692 $text = $this->general->replace( $text );
4693 $text = $this->nowiki->replace( $text );
4694 } while ( $text !== $oldText );
4695 wfProfileOut( __METHOD__ );
4696 return $text;
4697 }
4698 }
4699
4700 /**
4701 * @todo document, briefly.
4702 * @ingroup Parser
4703 */
4704 class OnlyIncludeReplacer {
4705 var $output = '';
4706
4707 function replace( $matches ) {
4708 if ( substr( $matches[1], -1 ) === "\n" ) {
4709 $this->output .= substr( $matches[1], 0, -1 );
4710 } else {
4711 $this->output .= $matches[1];
4712 }
4713 }
4714 }